Merge K Sorted Slices With A Heap
Keep one head element per slice in a min-heap and always pop the smallest, so k sorted slices merge in one pass without re-scanning.
Code
package main
import (
"container/heap"
"fmt"
)
// item pairs a value with the index of the sorted slice it came from
type item struct {
value int
src int
}
type minHeap []item
func (h minHeap) Len() int { return len(h) }
func (h minHeap) Less(i, j int) bool { return h[i].value < h[j].value }
func (h minHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
func (h *minHeap) Push(v any) { *h = append(*h, v.(item)) }
func (h *minHeap) Pop() any {
old := *h
n := len(old)
v := old[n-1]
*h = old[:n-1]
return v
}
// mergeKSorted: one head per slice in the heap, always pop the smallest
func mergeKSorted(slices [][]int) []int {
h := &minHeap{}
for i, s := range slices {
if len(s) > 0 {
*h = append(*h, item{value: s[0], src: i})
}
}
heap.Init(h)
pos := make([]int, len(slices))
var merged []int
for h.Len() > 0 {
it := heap.Pop(h).(item)
merged = append(merged, it.value)
pos[it.src]++
if pos[it.src] < len(slices[it.src]) {
heap.Push(h, item{value: slices[it.src][pos[it.src]], src: it.src})
}
}
return merged
}
func main() {
fmt.Println(mergeKSorted([][]int{{1, 4, 7}, {2, 5, 8}, {3, 6, 9}}))
fmt.Println(mergeKSorted([][]int{{}, {1}, {0, 2}}))
}What the file does
Structurally, expect the functions Len, Less, Swap and Push and nothing else.
for i, s := range slices is where the per-item work happens.
Caveats
- Standard-library through and through — paste it in and run.
Putting it to use
Entry signature: func (h minHeap) Len() int
main calls 1 helper in sequence: mergeKSorted.
Core lines
func (h minHeap) Less(i, j int) bool { return h[i].value < h[j].value }
func (h *minHeap) Push(v any) { *h = append(*h, v.(item)) }
func (h minHeap) Len() int { return len(h) }
Interactive Tools for This Topic
Big-O Complexity VisualizerVisualize and compare algorithm time complexities like O(1), O(log n), O(n), O(n log n), and O(n²). Plot growth curves to understand performance scaling at a glance.cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- How do you run Merge K Sorted Slices With A Heap?
- The runtime alone is enough: execute the file as a complete program.
Report a problem with this exampleOpens a pre-filled issue on GitHub.