package main
import "fmt"
func merge(arr []int, left, right, mid int) {
var temp []int // 辅助数组
// temp := []int{}
p1 := left
p2 := mid + 1
for p1 <= mid && p2 <= right {
if arr[p1] <= arr[p2] {
temp = append(temp, arr[p1])
p1++
} else {
temp = append(temp, arr[p2])
p2++
}
}
for p1 <= mid {
temp = append(temp, arr[p1])
p1++
}
for p2 <= right {
temp = append(temp, arr[p2])
p2++
}
// 将排序后的值拷贝到原数组
for i, val := range temp {
arr[left + i] = val
}
// for i := 0; i < len(temp); i++ {
// arr[left + i] = temp[i]
// }
}
func mergeSort(arr []int, left, right int) {
if left < right {
mid := (left + right) >> 1
mergeSort(arr, left, mid)
mergeSort(arr, mid + 1, right)
merge(arr, left, right, mid)
}
}
func main() {
arr := []int{3, 9, 1, 4, 7}
mergeSort(arr, 0, len(arr) - 1)
fmt.Println(arr)
}
go实现归并排序
最新推荐文章于 2024-08-01 09:15:00 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)