Created
October 23, 2012 16:52
-
-
Save julianshen/3940045 to your computer and use it in GitHub Desktop.
[Go] Concurrent merge sort
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" | |
func Merge(ldata []int, rdata []int) (result []int) { | |
result = make([]int, len(ldata) + len(rdata)) | |
lidx, ridx := 0, 0 | |
for i:=0;i<cap(result);i++ { | |
switch { | |
case lidx >= len(ldata): | |
result[i] = rdata[ridx] | |
ridx++ | |
case ridx >= len(rdata): | |
result[i] = ldata[lidx] | |
lidx++ | |
case ldata[lidx] < rdata[ridx]: | |
result[i] = ldata[lidx] | |
lidx++ | |
default: | |
result[i] = rdata[ridx] | |
ridx++ | |
} | |
} | |
return | |
} | |
func MergeSort(data []int, r chan []int) { | |
if len(data) == 1 { | |
r <- data | |
return | |
} | |
leftChan := make(chan []int) | |
rightChan := make(chan []int) | |
middle := len(data)/2 | |
go MergeSort(data[:middle], leftChan) | |
go MergeSort(data[middle:], rightChan) | |
ldata := <-leftChan | |
rdata := <-rightChan | |
close(leftChan) | |
close(rightChan) | |
r <- Merge(ldata, rdata) | |
return | |
} | |
func main() { | |
s := []int{22, 8, 3, 31, 4, 2, 42, 1, 16, 6, 11, 25, 9, 8, 10, 12, 18, 14, 7, 15} | |
result := make(chan []int) | |
go MergeSort(s, result) | |
r := <- result | |
for _,v := range r { | |
fmt.Println(v) | |
} | |
close(result) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi Julian,
May I use the merge and mergeSort of your codes published above in my homework assignment please? Coursera 3rd Course Concurrency, Week3 assignment.
I am seeking your permissions before I made modifications on my own integer inputs, but I shall use the merge() and mergeSort() of yours. With proper reference of course. Subject to your kind permission.
Thank you in advance!
Regards
Edward Hsu
edwardcy.hsu@gmail.com | +65 9029 3182