Created
September 29, 2017 16:19
-
-
Save kayslay/82eeb286654a959c5b1181cc9e4a949f to your computer and use it in GitHub Desktop.
merge sort using Golang
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" | |
) | |
var ( | |
list []int = []int{838, 23, 83, 64, 83, 23, 63, 90, 50, 20, 20, 4, 30, 5, 2, 50, 190, 19, 3, 70, 21, 3, 20, 28, 93, 39, 838, 23, 83, 64, 83, 23, 63, 90, 50, 20} | |
) | |
func main() { | |
c := make(chan []int) | |
go func() { | |
c <- Merge(list) | |
}() | |
fmt.Println(<-c) | |
} | |
func join(l, r []int) []int { | |
var out []int = make([]int, 0, len(l)+len(r)) | |
for len(l) > 0 || len(r) > 0 { | |
if len(l) == 0 { | |
return append(out, r...) | |
} else if len(r) == 0 { | |
return append(out, l...) | |
} else if l[0] <= r[0] { | |
out = append(out, l[0]) | |
l = l[1:] | |
} else if l[0] > r[0] { | |
out = append(out, r[0]) | |
r = r[1:] | |
} | |
} | |
return out | |
} | |
func Merge(list []int) []int { | |
var left, right <-chan []int | |
if len(list) <= 1 { | |
return list | |
} | |
left = makeChan(Merge, list[len(list)/2:len(list)]) | |
right = makeChan(Merge, list[:len(list)/2]) | |
return join(<-left, <-right) | |
} | |
func makeChan(a func([]int) []int, l []int) <-chan []int { | |
c := make(chan []int) | |
go func() { c <- a(l) }() | |
return c | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment