Created
October 26, 2018 01:39
-
-
Save geowa4/ba8abf266c69707765fab973538caa64 to your computer and use it in GitHub Desktop.
Merge Sort in Go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"math/rand" | |
) | |
func fill(size int) []int { | |
slice := make([]int, 0, size) | |
for i := 0; i < size; i++ { | |
slice = append(slice, int(rand.Float32()*10)) | |
} | |
return slice | |
} | |
func merge(a []int, b []int) []int { | |
aLen, bLen := len(a), len(b) | |
totalLen := aLen + bLen | |
c := make([]int, 0, totalLen) | |
aIndex, bIndex := 0, 0 | |
for i := 0; i < totalLen; i++ { | |
if aIndex == aLen { | |
c = append(c, b[bIndex]) | |
bIndex++ | |
} else if bIndex == bLen { | |
c = append(c, a[aIndex]) | |
aIndex++ | |
} else if a[aIndex] < b[bIndex] { | |
c = append(c, a[aIndex]) | |
aIndex++ | |
} else { | |
c = append(c, b[bIndex]) | |
bIndex++ | |
} | |
} | |
return c | |
} | |
func sort(unordered []int) []int { | |
length := len(unordered) | |
if length <= 1 { | |
return unordered | |
} | |
pivot := length / 2 | |
a := unordered[0:pivot] | |
b := unordered[pivot:length] | |
return merge(sort(a), sort(b)) | |
} | |
func main() { | |
a, b, c := fill(100), fill(1), fill(0) | |
fmt.Println(a) | |
fmt.Println(sort(a)) | |
fmt.Println(b) | |
fmt.Println(sort(b)) | |
fmt.Println(c) | |
fmt.Println(sort(c)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment