-
Notifications
You must be signed in to change notification settings - Fork 0
/
merge.go
66 lines (58 loc) · 1.37 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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package sorter
// MergeSort divides the unsorted list sublists that containing 1 element
// After this process, gets these each of list that has 1 element
// and merge sublists repeatedly to produce new sorted sublists
// This process will last until there is only 1 sublist remaining
// This remaining list will be sorted list.
//
// In example ; Assume an array has {4,3,6,2,9,8}
// After MergeSort called
// we have 2 sublists that have for left {4,3,6} and for right {2,9,8}
// List will look like this
// {4,3,6,2,9,8}
// {4,3,6}---------------|-----------{2,9,8}
// {4}--------|------{3,6} {2}---------|---------{9,8}
// {4} {3}--|--{6} {2} {9}---|---{8}
//
//
//---- After this section
//
// Merge will work to bring together the sublists as sorted
func MergeSort(arr []int) []int {
if len(arr) < 2 {
return arr
}
mid := len(arr) / 2
left := arr[:mid]
right := arr[mid:]
l := MergeSort(left)
r := MergeSort(right)
merge := Merge(l, r)
return merge
}
// Merge merges the 2 arrays
func Merge(left, right []int) []int {
arr := make([]int, len(left)+len(right))
var i, j, k int
for i < len(left) && j < len(right) {
if left[i] < right[j] {
arr[k] = left[i]
i++
} else {
arr[k] = right[j]
j++
}
k++
}
for i < len(left) {
arr[k] = left[i]
i++
k++
}
for j < len(right) {
arr[k] = right[j]
j++
k++
}
return arr
}