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
| func merge(vals []int, helper []int, low int, middle int, high int) {
//copy both halves into helper slice
for i := low; i <= high; i++ {
helper[i] = vals[i]
}
helperLeft := low
helperRight := middle + 1
current := low
//iterate through helper array. Compare left and right
// half, copying the smaller of the 2 into original
for helperLeft <= middle && helperRight <= high {
if helper[helperLeft] <= helper[helperRight] {
vals[current] = helper[helperLeft]
helperLeft++
} else {
vals[current] = helper[helperRight]
helperRight++
}
current++
}
// Copy the rest of the left side of the array into the
// target array.
remaining := middle - helperLeft
for i := 0; i <= remaining; i++ {
vals[current+i] = helper[helperLeft+i]
}
}
func mergesort(vals []int, helper []int, low int, high int) {
if low < high {
middle := (low + high) / 2
mergesort(vals, helper, low, middle)
mergesort(vals, helper, middle+1, high)
merge(vals, helper, low, middle, high)
}
}
func MergeSort(vals []int) {
helper := make([]int, len(vals))
mergesort(vals, helper, 0, len(vals)-1)
}
|