归并排序
1.归并排序的思想
归并排序的思想就是将已经有序的子序列合并,得到另一个有序的数列。通过不断地递归,将原数组分割为若干个有序的数组,分割完成后再不断进行合并。
归并排序需要额外的空间来存放排序的结果。
2.归并排序的代码实现(Go语言)
介绍了归并排序的具体实现过程。
//有序数组的合并,
func merge(left []int,right []int) []int { //传入两个数组,分别为left和right
res := make([]int,0,len(left) + len(right)) //定义一个切片,其容量为两个数组的长度之和
for len(left) != 0 && len(right) != 0 { //开始循环,将左右数组的第一个元素中较小的放入结果切片中
if left[0] >= right[0] {
res = append(res, right[0])
right = right[1:] //放入结果之后,将原数组的第一个元素删除
}else {
res = append(res, left[0])
left = left[1:]
}
}
// 当左右某个数组的长度为0时,循环结束
if len(left) == 0 { //将另一个数组追加到结果切片之后,合并完成
res = append(res, right...)
}else {
res = append(res, left...)
}
return res
}
//归并排序的实现
func