Last active
April 5, 2019 11:09
-
-
Save sagivo/2983f18ffb811b2fec8b to your computer and use it in GitHub Desktop.
mergesort 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
func merge_sort(l []int) []int { | |
if len(l) < 2 { | |
return l | |
} | |
mid := len(l) / 2 | |
a := merge_sort(l[:mid]) | |
b := merge_sort(l[mid:]) | |
return merge(a, b) | |
} | |
func merge(left, right []int) []int { | |
var i, j int | |
result := make([]int, len(left)+len(right)) | |
for i < len(left) && j < len(right) { | |
if left[i] <= right[j] { | |
result[i+j] = left[i]; i++ | |
} else { | |
result[i+j] = right[j]; j++ | |
} | |
} | |
for i < len(left) {result[i+j] = left[i]; i++} | |
for j < len(right) {result[i+j] = right[j]; j++ } | |
return result | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment