编程语言
首页 > 编程语言> > Go-实现插入排序算法

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