-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmerge.go
61 lines (47 loc) · 936 Bytes
/
merge.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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package sorting
/*
https://blog.boot.dev/golang/merge-sort-golang
https://github.com/algorithms-go/merge-sort
Divide and Conquer algo
MergeSort() -> recursive
1. Divide array into 2 equal parts
2. Call itself on these 2 parts
3. Merge() call to fit these 2 halves back together
Best: O(n logn)
Worst: O(n logn)
Space: O(n)
1. Extra memory
2. Recursive
3. Stable Sort
*/
func MergeSort(items []int) []int {
length := len(items)
if length <= 1 {
return items
}
mid := length / 2
left := MergeSort(items[:mid])
right := MergeSort(items[mid:])
return merge(left, right)
}
func merge(a, b []int) []int {
i := 0
j := 0
final := []int{}
for i < len(a) && j < len(b) {
if a[i] < b[j] {
final = append(final, a[i])
i++
} else {
final = append(final, b[j])
j++
}
}
for ; i < len(a); i++ {
final = append(final, a[i])
}
for ; j < len(b); j++ {
final = append(final, b[j])
}
return final
}