-
Notifications
You must be signed in to change notification settings - Fork 267
/
merge_sort.go
57 lines (46 loc) · 981 Bytes
/
merge_sort.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
package main
import "fmt"
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++
} else {
slice[k] = sliceRightSide[j]
j++
}
k++
}
for i < len(sliceLeftSide) {
slice[k] = sliceLeftSide[i]
i++
k++
}
for j < len(sliceRightSide) {
slice[k] = sliceRightSide[j]
j++
k++
}
}
}
func main() {
slice := []int{4, 6, 7, 1, 2, 3, 5, 9, 8}
fmt.Println("Slice:", slice)
MergeSort(slice)
fmt.Println("MergeSort:", slice)
}