我有一個[]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 []bytefunc (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(或事后排序)。returnObjobj.ByteDatareturnOjb
1 回答

慕工程0101907
TA貢獻1887條經驗 獲得超5個贊
在每次迭代中,執行以下操作:
增長目標切片(可能重新分配它):
numElems := len(returnObj)
returnObj = append(returnObj, make([]byte, len(obj))...)
使用標準的插入方法通過找到一個位置來逐個放置源切片中的每個字節來保持目標排序:
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應該通過減少復制來優化對的調用,但這留給讀者作為練習。)
- 1 回答
- 0 關注
- 157 瀏覽
添加回答
舉報
0/150
提交
取消