我有一個(gè)[]byte我需要按升序排序。我得到一個(gè)包含項(xiàng)目的對象,然后迭代數(shù)組以創(chuàng)建返回的對象:// 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}所以我問自己是否有可能立即進(jìn)行排序,或者我是否需要預(yù)先排序append(或事后排序)。returnObjobj.ByteDatareturnOjb
1 回答
慕工程0101907
TA貢獻(xiàn)1887條經(jīng)驗(yàn) 獲得超5個(gè)贊
在每次迭代中,執(zhí)行以下操作:
增長目標(biāo)切片(可能重新分配它):
numElems := len(returnObj)
returnObj = append(returnObj, make([]byte, len(obj))...)
使用標(biāo)準(zhǔn)的插入方法通過找到一個(gè)位置來逐個(gè)放置源切片中的每個(gè)字節(jié)來保持目標(biāo)排序:
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應(yīng)該通過減少復(fù)制來優(yōu)化對的調(diào)用,但這留給讀者作為練習(xí)。)
- 1 回答
- 0 關(guān)注
- 169 瀏覽
添加回答
舉報(bào)
0/150
提交
取消
