generated from eng618/template
-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
merge.go
46 lines (40 loc) · 1.19 KB
/
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
// Package sort is a collection of sortting algorithms
//
// See https://visualgo.net/en/sorting for a visual example of merge sort.
package sort
// MergeSort takes the provided data (slice of int) and applies the merge sort algorithm, to sort the data.
// The runtime of merge sort is at best, at worst, and at average always O(n * logn).
func MergeSort(d []int) []int {
// base case
if len(d) <= 1 {
return d
}
// split data into 2 halves
middle := len(d) / 2
left := d[:middle]
right := d[middle:]
// recursively merge sorted sides
return Merge(MergeSort(left), MergeSort(right))
}
// Merge takes two slice of ints (assuming they are sorted) and merges them
// into a single slice. If the the inputs are sorted, the resulting merge will
// preserve the correct sorted order.
//
// If the slices are not sorted the resulting slice will have unpredictable
// results.
func Merge(l, r []int) []int {
result := make([]int, len(l)+len(r))
// Add items to result until either side is empty.
li, ri, i := 0, 0, 0
for li < len(l) || ri < len(r) {
if li < len(l) && (ri == len(r) || l[li] < r[ri]) {
result[i] = l[li]
li++
} else {
result[i] = r[ri]
ri++
}
i++
}
return result
}