归并排序实现思路:
第一步:分解数组。递归分解数组,采取二分法不断分到最小(数组长度为0或1)
第二步:比较大小。将两个数组进行大小比较,从第一位开始,小的放入归并的数组中。
第三步:归并。将所有子数组进行归并,采取递归的方式。
核心代码如下:
package basicAlgorithm
func MergeSort(arr []int) []int {
if len(arr) <= 1 {
return arr
}
middle := len(arr) / 2
left := MergeSort(arr[:middle])
right := MergeSort(arr[middle:])
return Merge(left, right)
}
func Merge(left, right []int) []int {
temp := make([]int, 0, len(left)+len(right))
i, j := 0, 0
for i < len(left) && j < len(right) {
if left[i] < right[j] {
temp = append(temp, left[i])
i++
} else {
temp = append(temp, right[j])
j++
}
}
temp = append(temp, left[i:]...)
temp = append(temp, right[j:]...)
return temp
}
分析:
分解数组采取二分法,故取长度除以2,同时采用递归不断分解数组,直到分解到其长度为0或1
middle := len(arr) / 2
left := MergeSort(arr[:middle])
right := MergeSort(arr[middle:])
比较数组的大小,需要两个指针,指向较小的数把数取出来,然后存入临时数组中,而这个临时数组的长度等于传进来的两个数组的长度和,然后把这个取出数值的指针向后移动一位。
temp := make([]int, 0, len(left)+len(right))
i, j := 0, 0
for i < len(left) && j < len(right) {
if left[i] < right[j] {
temp = append(temp, left[i])
i++
} else {
temp = append(temp, right[j])
j++
}
}
当然存在一方指针先到达最后,那么就会退出循环,需要把另一个数组中的值取出来放入临时数组中。
temp = append(temp, left[i:]...)
temp = append(temp, right[j:]...)
最后通过递归完成数组的归并。