func main() {
ch1 := create([]int{1, 3, 6})//待排序的管道1
ch2 := create([]int{2, 5, 9})//待排序的管道2
ch := merge(ch1, ch2)
for c := range ch {
fmt.Println(c)
}
for {
runtime.GC()
}
}
func create(arr []int) chan int {
out := make(chan int)
go func() {
for _, v := range arr {
out <- v
}
close(out)
}()
return out
}
func merge(ch1, ch2 chan int) chan int {
ch := make(chan int)
go func() {
v1, ok1 := <-ch1
v2, ok2 := <-ch2
for {
if ok1 || ok2 {
if ok1 && ok2 {
if v1 < v2 {
ch <- v1
v1, ok1 = <-ch1
} else {
ch <- v2
v2, ok2 = <-ch2
}
} else if ok1 && !ok2 {
ch <- v1
v1, ok1 = <-ch1
} else {
ch <- v2
v2, ok2 = <-ch2
}
} else {
close(ch)
break
}
}
}()
return ch
}