Golang-排序演算法

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

状况

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

做法

for-交换排序法

  • 时间复杂度=(1+N)*N/2=N^2
  • 优点:省空间
  • 缺点:花时间
package main

type Sample struct {
	Name    string
	OrderID int
}

var sample [100]Sample

func 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 main

type Sample struct {
	Name    string
	OrderID int
}

var sample [100]Sample

func OrderValue() {
	outputSample := make([]Sample, len(sample))

	for index := range sample {
		outputIndex := sample[index].OrderID
		outputSample[outputIndex] = sample[index]
	}
}

总结

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


<<:  EXCEL VBA SQL 将资料 汇出 到dBASEIII .dbf档案

>>:  Azure CDN (akamai) 强制置换图片教学

[DAY 1] 前言

大家好,我是Billy,身为资讯人,在对一项技术深入研究才会发现,自己不了解的更多,所以尝试以参加铁...

(Day27) ESM 模组化拆档

前言 随者前端需求越来越多,前端工程师在管理程序码上的需求也越来越重,幸好 ES6 引入时 Java...

RXDB connect to React Component

Demo /** * Sample React Native App * https://githu...

网路流量统计分析 NTOP 後继版本 NTOPNG for Windows 10 20H2 的版本安装设定教学 Ntopng Windows install

网路流量统计分析 NTOP 後继版本 NTOPNG for Windows 10 20H2 的版本安...

[Day 30] 资安自学之路 小成长

想分享一些我受惠过的资源: 高中职生资安研习营 https://www.facebook.com/s...