diff --git a/main.go b/main.go index 9309b3d..6a7791e 100644 --- a/main.go +++ b/main.go @@ -56,7 +56,7 @@ func merge(cs ...<-chan int) <-chan int { out := make(chan int) go func() { - h := &IntHeap{} + h := &items{} heap.Init(h) // prime the pumps @@ -89,28 +89,30 @@ func merge(cs ...<-chan int) <-chan int { return out } -// An IntHeap is a min-heap of ints. -type IntHeap []item +// item keeps track of an integer value and the index of its source. +// +// the index is used to chose the next source to use when a value has been +// pulled. +type item struct { + val int + src int +} -func (h IntHeap) Len() int { return len(h) } -func (h IntHeap) Less(i, j int) bool { return h[i].val < h[j].val } -func (h IntHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] } +// items is a min-heap of item. +type items []item -func (h *IntHeap) Push(x interface{}) { - // Push and Pop use pointer receivers because they modify the slice's length, - // not just its contents. +func (h items) Len() int { return len(h) } +func (h items) Less(i, j int) bool { return h[i].val < h[j].val } +func (h items) Swap(i, j int) { h[i], h[j] = h[j], h[i] } + +func (h *items) Push(x interface{}) { *h = append(*h, x.(item)) } -func (h *IntHeap) Pop() interface{} { +func (h *items) Pop() interface{} { old := *h n := len(old) x := old[n-1] *h = old[0 : n-1] return x } - -type item struct { - val int - src int -}