Golang-排序演算法

这篇文章算是做个纪录
把工作上遇到的问题,想到其他的解法记录下来

状况

资料因为从map取得,处理过后进到array,而传递到前端时是无序状态需要将资料做排序,而资料带有OrderID,且OrderID不重複

做法

for-交换排序法

时间複杂度=(1+N)*N/2=N^2优点:省空间缺点:花时间
package maintype Sample struct {Name    stringOrderID int}var sample [100]Samplefunc OrderValue() {for i := 0; i < len(sample); i++ {for j := i + 1; j < len(sample); j++ {if sample[i].OrderID > sample[j].OrderID {temp := sample[i]sample[i] = sample[j]sample[j] = temp}}}}

用空间换时间

时间複杂度=O(N)优点:省时间缺点:花空间
package maintype Sample struct {Name    stringOrderID int}var sample [100]Samplefunc OrderValue() {outputSample := make([]Sample, len(sample))for index := range sample {outputIndex := sample[index].OrderIDoutputSample[outputIndex] = sample[index]}}

总结

用空间换时间是洗澡的时候突然想到的XD
原理就是利用OrderID做为新阵列的index
最后再将该资料插入新阵列


关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章