-
Notifications
You must be signed in to change notification settings - Fork 2
/
mergesort.go
47 lines (39 loc) · 853 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
36
37
38
39
40
41
42
43
44
45
46
47
package main
// Sort an array of distinct elements
// Array length may be odd or even
func mergeSort(args []int) []int {
lengthOfArgs := len(args)
// Base case
if lengthOfArgs <= 1 {
return args
}
// find a middle point
breakpoint := lengthOfArgs / 2
return merge(mergeSort(args[:breakpoint]), mergeSort(args[breakpoint:]))
}
func merge(left, right []int) []int {
var (
size = len(left) + len(right)
i = 0
j = 0
ret = make([]int, size, size)
)
for k := 0; k < size; k++ {
// handle odd number of elements
if i > len(left)-1 && j <= len(right)-1 {
ret[k] = right[j]
j++
} else if j > len(right)-1 && i <= len(left)-1 {
ret[k] = left[i]
i++
// compare and sort by lowest element
} else if left[i] < right[j] {
ret[k] = left[i]
i++
} else {
ret[k] = right[j]
j++
}
}
return ret
}