Sub topic 13
Merging sorted streams
This chapter assumes you can use heapq, know that push and pop cost O(log n), and can read Python generators. Here you will merge k sorted inputs into one sorted output with a heap that holds at most k items.
The problem
Suppose you have k sorted sources, such as log files sorted by timestamp, or the sorted runs produced by an external sort. You want one sorted sequence.
The simple approach is to concatenate everything and sort it. That costs O(N log N) for N total items. It also needs all N items in memory, and it ignores the fact that each input is already sorted.
A heap does better. The smallest unmerged item overall must be the front item of one of the k streams. So the heap only needs to hold one front item per stream.
The algorithm
- Take the first item from each stream and put it in a min-heap.
- Pop the smallest item and output it.
- Take the next item from the stream that item came from, and push it.
- Repeat until the heap is empty.
Each output item costs one heap operation on a heap of size at most k. The total time is O(N log k), and the extra memory is O(k), regardless of N.
Implementation
Each heap entry is a tuple (value, stream_index, iterator). The iterator tells us where to refill from. The unique stream_index settles ties, so Python never has to compare two iterators, which would raise a TypeError.
import heapq
def merge_sorted(*streams):
heap = []
for i, stream in enumerate(streams):
it = iter(stream)
for first in it: # runs at most once; skips empty streams
heap.append((first, i, it))
break
heapq.heapify(heap)
while heap:
value, i, it = heap[0]
yield value
for nxt in it:
heapq.heapreplace(heap, (nxt, i, it))
break
else: # stream exhausted
heapq.heappop(heap)
print(list(merge_sorted([1, 4, 7], [2, 5], [], [3, 6, 9])))
# [1, 2, 3, 4, 5, 6, 7, 9]Two details matter here:
heapreplacepops the smallest entry and pushes the new one in a single sift. That is cheaper than a separate pop and push.- The function is a generator, so it produces output lazily. It never holds more than one pending item per stream, which makes it suitable for inputs larger than memory.
Using the standard library
You rarely need to write this yourself. heapq.merge implements the same idea.
import heapq
a = [1, 4, 7]
b = [2, 5]
c = [3, 6, 9]
print(list(heapq.merge(a, b, c)))
# [1, 2, 3, 4, 5, 6, 7, 9]
# Descending inputs need reverse=True; key works like it does in sorted()
words = ["pear", "fig", "banana"], ["kiwi", "plum", "cherry"]
print(list(heapq.merge(*words, key=len)))
# ['fig', 'pear', 'kiwi', 'plum', 'banana', 'cherry']When values compare equal, heapq.merge emits items from earlier streams first, so the merge is stable.
Common errors
- Unsorted input. The merge does not check that its inputs are sorted. With unsorted input you get output that looks plausible but is not sorted. Make sure each stream is already sorted by the same key and in the same direction.
- Comparing iterators. A heap entry like
(value, it)fails on ties. Always put a unique integer between the value and the iterator. - Mixing directions. If one stream is ascending and another descending, the result is meaningless.
Where it appears
External merge sort writes sorted chunks to disk, then merges them with this algorithm. Databases and log pipelines merge sorted shards the same way. It is also the standard way to merge k sorted linked lists.
Exercise
You merge 8 sorted files with 1,000,000 lines each, using a heap. About how many comparisons does each output line cost, and how many lines are held in memory at once?
Show answer
Each output line costs about log2(8) = 3 levels of heap work, so roughly 3 to 6 comparisons per sift. At most 8 lines are in memory at once, one per file. The total work is O(N log k) with N = 8,000,000 and k = 8.