-
Notifications
You must be signed in to change notification settings - Fork 0
/
mergesort.go
35 lines (33 loc) · 816 Bytes
/
mergesort.go
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
package sort
// MergeSort is an efficient, general-purpose, comparison-based sorting algorithm.
func MergeSort(arr *[]int, left int, right int) []int {
if (right - left) <= 1 {
middle := left + (right-left)>>1
return (*arr)[middle : middle+1]
}
middle := left + (right-left)>>1
leftPart := MergeSort(arr, left, middle)
rightPart := MergeSort(arr, middle+1, right)
// merge two sorted array :)
result := make([]int, right-left)
i := 0
j := 0
for i < len(leftPart) && j < len(rightPart) {
if leftPart[i] <= rightPart[j] {
result = append(result, leftPart[i])
i++
} else {
result = append(result, rightPart[j])
j++
}
}
for i < len(leftPart) {
result = append(result, leftPart[i])
i++
}
for j < len(rightPart) {
result = append(result, rightPart[j])
j++
}
return result
}