arrays - 附加到切片时排序?
问题描述
我有一个[]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
事后排序)。
解决方案
在每次迭代中,执行以下操作:
增长目标切片(可能重新分配它):
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
应该通过减少复制来优化调用,但这留给读者练习。)
推荐阅读
- python - Keras - 将图像从生成器加载到内存中
- intellij-idea - 从无处不在的搜索结果中隐藏运行配置
- typo3 - TYPO3 - 如何在没有 Transl.Orig 的情况下显示已翻译的新闻?
- python - 使用外推/插值调整数组大小
- elasticsearch - Elasticsearch 6 映射创建抛出错误
- matlab - 如何规划从点 1 到点 2 的路径,使其保持在指定区域?
- javascript - 使用 flexbox 垂直对齐内容
- c# - Xamarin.Forms:独立于平台的应用程序菜单
- ios - 如何将数据从一个视图控制器传递到另一个在 json 中获取并需要在 tableview 中设置的视图控制器?
- r - 在R中循环,提取输出的最后一行