Skip to content

Commit 41994c1

Browse files
committed
Merge pull request blakeembrey#136 from Dokko1230/master
add merge-sort for go
2 parents 88f0341 + 88a1b5f commit 41994c1

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

solutions/go/merge-sort.go

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
package main
2+
3+
import (
4+
"fmt"
5+
"math"
6+
)
7+
8+
func mergeSort(ary []int) []int {
9+
if len(ary) <= 1 {
10+
return ary
11+
}
12+
left := make([]int, 0)
13+
right := make([]int, 0)
14+
middle := math.Floor(float64(len(ary) / 2))
15+
16+
left = ary[0:int(middle)]
17+
right = ary[int(middle):]
18+
19+
return merge(mergeSort(left), mergeSort(right))
20+
}
21+
22+
func merge(left, right []int) []int {
23+
24+
result := make([]int, 0)
25+
26+
for len(left) > 0 || len(right) > 0 {
27+
if len(left) > 0 && len(right) > 0 {
28+
if left[0] <= right[0] {
29+
result = append(result, left[0])
30+
left = left[1:len(left)]
31+
} else {
32+
result = append(result, right[0])
33+
right = right[1:len(right)]
34+
}
35+
} else if len(left) > 0 {
36+
result = append(result, left[0])
37+
left = left[1:len(left)]
38+
} else {
39+
result = append(result, right[0])
40+
right = right[1:len(right)]
41+
}
42+
}
43+
44+
return result
45+
}
46+
47+
func main() {
48+
random := []int{1,73,7,1,72,58,933,574,24,74,52}
49+
fmt.Println("Unsorted: ", random)
50+
random = mergeSort(random)
51+
fmt.Println("Sorted: ", random)
52+
}

0 commit comments

Comments
 (0)