forked from kelvins/algorithms-and-data-structures
-
Notifications
You must be signed in to change notification settings - Fork 1
/
mergesort.go
48 lines (39 loc) · 872 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
48
package mergesort
func MergeSort(slice []int) {
if len(slice) > 1 {
half := len(slice) / 2
var sliceLeftSide []int
var sliceRightSide []int
for index := 0; index < half; index++ {
sliceLeftSide = append(sliceLeftSide, slice[index])
}
for index := half; index < len(slice); index++ {
sliceRightSide = append(sliceRightSide, slice[index])
}
MergeSort(sliceLeftSide)
MergeSort(sliceRightSide)
i := 0
j := 0
k := 0
for i < len(sliceLeftSide) && j < len(sliceRightSide) {
if sliceLeftSide[i] < sliceRightSide[j] {
slice[k] = sliceLeftSide[i]
i = i + 1
} else {
slice[k] = sliceRightSide[j]
j = j + 1
}
k = k + 1
}
for i < len(sliceLeftSide) {
slice[k] = sliceLeftSide[i]
i = i + 1
k = k + 1
}
for j < len(sliceRightSide) {
slice[k] = sliceRightSide[j]
j = j + 1
k = k + 1
}
}
}