上一篇文章写的十分的烂,经过科普看语言源码实现用的是quicksort实现的底层排序,在这里模仿一下,勿喷!
package main import ( "fmt" "math/rand" "runtime" "sort" "time" ) func mergeonce(l,r []int) []int { m := make([]int,len(l)+len(r)) i,j := 0,0 if i < len(l) && j < len(r) { for { if l[i] < l[j] { m = append(m,l[i]) i++ if i == len(l) { break } } else { m = append(m,l[j]) j++ if j == len(r) { break } } } } m = append(append(m,l[i:]...),r[j:]...) return m } func merge(in chan []int,out chan []int) { var next chan []int var l []int for list := range in { if l == nil { l = list continue } r := list if next == nil { next = make(chan []int,1) go merge(next,out) } next <- mergeonce(l,r) l = nil } if next == nil { out <- l } else { if l != nil { next <- l } close(next) } } func main() { runtime.GOMAXPROCS(2) ch := make(chan []int,1) const Num = 100 const WNum = 100 fmt.Println(time.Now()) go func(n int,out chan []int) { for i := 0; i < n; i++ { list := make([]int,1000) for j := range list { list[j] = rand.Int() } sort.Ints(list) out <- list } close(out) }(Num*WNum,ch) out := make(chan []int) go merge(ch,out) list := <-out fmt.Println(time.Now()) fmt.Println(len(list)) fmt.Println(sort.IntsAreSorted(list)) }