6

【代码】Go语言插入排序

 1 year ago
source link: https://loli.fj.cn/2023/06/03/Go%E8%AF%AD%E8%A8%80%E6%8F%92%E5%85%A5%E6%8E%92%E5%BA%8F/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

通过Go语言实现插入排序
先将第一个数据作为逻辑上已经完成排序的逻辑子数组
将数组从第二个数据开始遍历所有数据,每次遍历时,对比当前数据是不是已完成排序的子数组中某一个位置的数据较小(较大)的一个数,如果不是已完成排序的子数组中某一个位置的数据较小的数,就将当前遍历的数据放到该位置
在逻辑子数组中向前移动位置时,每次都将该位置的数据向后移一位,为了将无序的数据插入到有序的数组中
如果逻辑子数组中移动的位置超出了第一个位置,说明第一个位置就是合适的位置,就将当前遍历的无序的数据插入到有序的数组中

从小到大递增

func insertSortDesc(arr []int) {
for i := 0; i < len(arr); i++ {
var insertNumber int = arr[i]
var insertIndex int = i - 1
for insertIndex >= 0 && arr[insertIndex] < insertNumber {
arr[insertIndex+1] = arr[insertIndex]
insertIndex -= 1
}
if insertIndex+1 != i {
arr[insertIndex+1] = insertNumber
}
}
}

从大到小递减

func insertSortAsc(arr []int) {
for i := 0; i < len(arr); i++ {
var insertNumber int = arr[i]
var insertIndex int = i - 1
for insertIndex >= 0 && arr[insertIndex] > insertNumber {
arr[insertIndex+1] = arr[insertIndex]
insertIndex -= 1
}
if insertIndex+1 != i {
arr[insertIndex+1] = insertNumber
}
}
}

哔哩哔哩——尚硅谷


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK