代码之家  ›  专栏  ›  技术社区  ›  unsafe_where_true

附加到切片时进行排序?

  •  2
  • unsafe_where_true  · 技术社区  · 7 年前

    我有一个 []byte 我需要按升序排序。

    我获取一个包含这些项的对象,然后迭代数组以创建返回的对象:

    // unfortunately, for some obscure reason I can't change the data types of the caller and the object from the function call are different, although both are []byte underneath (...)
    
    type ID []byte
    // in another package:
    type ByteInterface []byte
    
    
    func (c *Store) GetAll() ByteInterface {
      returnObj := make([]ByteInterface,0)
      obj, err := GetData()
      // err handling
      for _, b := range obj.IDs {
         returnObj = append(returnObj, ByteInterface(b))
      }
      return returnObj
    }
    

    所以我在问自己,是否有可能做到这一点 append 因此 returnObj 立即排序,或者如果我需要排序 obj.ByteData returnOjb

    1 回复  |  直到 7 年前
        1
  •  5
  •   kostix    7 年前

    1. 增长目标切片(可能会重新分配):

      numElems := len(returnObj)
      returnObj = append(returnObj, make([]byte, len(obj))...)
      
    2. 使用插入的标准方法,通过逐个查找放置源片中每个字节的位置来保持目标的排序:

      for _, b := range obj {
        i := sort.Search(numElems, func (i int) bool {
          return returnObj[i] >= b
        }
        if i < numElems {
          copy(returnObj[i+1:], returnObj[i:])
        }
        returnObj[i] = b
        numElems++
      }
      

      (呼吁 copy