18/40
Part 5 of 8 · Merging and schedulingLearn and do
Merge sorted streams with one heap entry per stream
The second pattern. You have k sources, and each is already sorted: log files from k servers ordered by time, k sorted runs of a big sort, k rows of a sorted table. You want one sorted stream.
The heap holds each stream's front, and the smallest front goes out next
Only the front of each source can be next. So a heap holds one entry per source: its current front, and an iterator that hands out the rest of that source. Pop the smallest front, hand it out, and push the next item from the same source. merge_sorted in the editor does this. Here it is on four streams:
print(merge_sorted([[1, 4, 9], [2, 3, 10], [5, 6], []]))
Merge the streams [1, 4, 9], [2, 3, 10], [5, 6] and []. At most how many entries sit in the heap at once?
Pick one to see what it prints.
Pick an answer above to see the rest