1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
|
package sorts
// 归并排序
func MergeSort(arr []int) {
arrLen := len(arr)
if arrLen <= 1 {
return
}
mergeSort(arr, 0, arrLen-1)
}
func mergeSort(arr []int, start, end int) {
if start >= end {
return
}
mid := (start + end) / 2
mergeSort(arr, start, mid)
mergeSort(arr, mid+1, end)
merge(arr, start, mid, end)
}
func merge(arr []int, start, mid, end int) {
tmpArr := make([]int, end-start+1)
i := start
j := mid + 1
k := 0
for ; i <= mid && j <= end; k++ {
if arr[i] <= arr[j] {
tmpArr[k] = arr[i]
i++
} else {
tmpArr[k] = arr[j]
j++
}
}
for ; i <= mid; i++ {
tmpArr[k] = arr[i]
k++
}
for ; j <= end; j++ {
tmpArr[k] = arr[j]
k++
}
copy(arr[start:end+1], tmpArr)
}
|