Go-实现插入排序算法
作者:互联网
算法描述:
插入算法,从第一个数开始进行循环,插入到一个已经排序的数组中循环遍历所有元素,最终返回所有元素的排好的序列,时间复杂度为 O(n^2) 。
算法步骤:
- 选择一个数进行比较然后将比这个值小的元素插入这个值之前。
- 向后位移进行处理,直到数据处理完毕。
误区总结如下:
- 插入算法一定和冒泡算法区分开
- 插入算法是将需要的元素插入到当前元素之前
- 冒泡是两两交换将想要的元素置顶
代码片段如下:
package main
func InsertSort(ary []int) (returnAry []int) {
length, i := len(ary), 1
returnAry = append(returnAry, ary[0])
for i < length {
for j := 0; j < len(returnAry); j++ {
if ary[i] <= returnAry[j] {
returnAry = InsertAry(returnAry, j, ary[i])
break
}
if j == len(returnAry)-1 && ary[i] > returnAry[j] {
returnAry = InsertAry(returnAry, j+1, ary[i])
break
}
}
i++
}
return
}
func InsertAry(ary []int, i, val int) (returnAry []int) {
num := 0
if len(ary) == i {
return append(returnAry, val)
}
for num < len(ary) {
if num < i {
returnAry = append(returnAry, ary[num])
} else if num == i {
returnAry = append(returnAry, val)
returnAry = append(returnAry, ary[num])
} else {
returnAry = append(returnAry, ary[num])
}
num++
}
return
}
标签:returnAry,int,ary,插入排序,算法,num,Go,append 来源: https://blog.csdn.net/luyaran/article/details/119384943