首页 > 解决方案 > 附加到切片时排序?

问题描述

我有一个[]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事后排序)。

标签: arrayssortinggo

解决方案


在每次迭代中,执行以下操作:

  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应该通过减少复制来优化调用,但这留给读者练习。)


推荐阅读