Last active
August 29, 2015 14:16
-
-
Save soroushjp/4b67cce316064b00aec6 to your computer and use it in GitHub Desktop.
Short, readable, recursive implementation of Mergesort in Golang using slices
This file contains hidden or 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
// Mergesort | |
package main | |
import "fmt" | |
func Push(front int, rest []int) []int { | |
new := make([]int, len(rest)+1) | |
copy(new[1:], rest) | |
new[0] = front | |
return new | |
} | |
func Merge(a, b []int) []int { | |
if len(a) == 0 { | |
return b | |
} | |
if len(b) == 0 { | |
return a | |
} | |
if a[0] < b[0] { | |
return Push(a[0], Merge(a[1:], b)) | |
} else { | |
return Push(b[0], Merge(b[1:], a)) | |
} | |
} | |
func MergeSort(sRef *[]int) { | |
s := (*sRef) | |
if len(s) <= 1 { | |
return | |
} | |
median := (0 + (len(s) - 1)) / 2 | |
left := s[0 : median+1] | |
right := s[median+1:] | |
MergeSort(&left) | |
MergeSort(&right) | |
*sRef = Merge(left, right) | |
} | |
func main() { | |
// Uncomment to try out Merge function | |
// myTestSlice := []int{2,11,14,25,108,206} | |
// myTestSlice2 := []int{1,4,8,18,24,27,39,100} | |
// fmt.Println(Merge(myTestSlice, myTestSlice2)) | |
mySlice := []int{4, 235, 16, 3, 18, 74, 55, 29, 7, 646, 100, 82, 14, 66, 441, 12, 2} | |
MergeSort(&mySlice) | |
fmt.Println(mySlice) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment