Skip to content

Instantly share code, notes, and snippets.

@jeremyBanks
Created June 13, 2011 14:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jeremyBanks/1022871 to your computer and use it in GitHub Desktop.
Save jeremyBanks/1022871 to your computer and use it in GitHub Desktop.
package main
import "fmt"
func MergeChannels(a chan int, b chan int) chan int {
// Merges two channels of sorted ints.
output := make(chan int)
go func() {
defer close(output)
nextA, hasA := <-a
nextB, hasB := <-b
for {
if !(hasA || hasB) {
break
} else if hasA && (!hasB || nextA <= nextB) {
output <- nextA
nextA, hasA = <-a
} else {
output <- nextB
nextB, hasB = <-b
}
}
}()
return output
}
func main() {
a := make(chan int, 5) // ", 5" adds a buffer, otherwise I couldn't just
b := make(chan int, 5) // shove in a bunch of values at once, as below.
merged := MergeChannels(a, b)
a <- 1
a <- 2
a <- 4
a <- 5
b <- 3
b <- 4
b <- 6
close(a)
close(b)
for value := range merged {
fmt.Print(value, " ")
}
fmt.Print("\n")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment