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.

GoData Integrity

Code

gosnippet
53 lines
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

FAQ

How do you run Merge K Sorted Slices With A Heap?
The runtime alone is enough: execute the file as a complete program.