Priority Queues and Multiway Merge
Remove items by priority and combine several already sorted streams.
priority queue, binary heap, heap operations, multiway mergeWhose turn is most urgent?
A normal queue gives the oldest waiting item the next turn. A priority queue gives the next turn to an item with the most important priority instead. The application defines whether a smaller or larger number means more important and how equal priorities are handled.
A binary heap is one way to implement a priority queue. In a min-heap, each parent is no greater than its children, so a smallest item is at the root. The tree is complete: every level is filled left to right before the next. Our heap and heap sort lesson uses the opposite, max-heap rule.
Follow heap operations
Start with this min-heap, stored as [2, 5, 4]:
2
/ \
5 4
Insert 1 at the next open position. Compare it with its parent and move it up
until the rule holds, giving [1, 2, 4, 5]. This is sifting up. To
remove the smallest item, replace the root with the last item and sift
down by exchanging it with a smaller child until the rule holds. The
resulting heap need not be fully sorted.
Merge more than two sorted streams
Imagine three shelves, each holding cards in ascending order:
A: [1, 6] B: [2, 5] C: [3, 4]
fronts: 1, 2, 3 -> take 1, then expose 6 from A
fronts: 6, 2, 3 -> take 2, then expose 5 from B
Keep the current front of each nonempty stream in a min-priority queue. Remove the smallest, output it, then replace it with the next item from the same stream if there is one. Repeat until all streams are exhausted. This is multiway merge. Empty streams contribute no fronts.
See the reasoning
Follow the example one step at a time
Insert 1 into a min-heap by sifting it up. This is a prepared teaching demonstration, not live code execution.
Start
heap: [2, 5, 4]
Each parent is no greater than its children, so the smallest item is at the root.
Python illustration
import heapq
heap = [2, 5, 4]
heapq.heappush(heap, 1)
print("smallest:", heap[0])
print("removed:", heapq.heappop(heap))
print("merged:", list(heapq.merge([1, 6], [2, 5], [3, 4])))
print("empty merge:", list(heapq.merge([], [])))
Prepared output — not live execution:
smallest: 1
removed: 1
merged: [1, 2, 3, 4, 5, 6]
empty merge: []
Python's heapq uses a min-heap represented by a list; it does not sort the
whole list. heappop and heap[0] raise IndexError on an empty heap.
heapq.merge returns an iterator and assumes each input is already sorted
in the requested direction. It does not sort unsorted inputs for you.
Time, space, and common mistakes
For n heap items, reading the root is O(1), inserting or removing it is
O(log n), and building a heap bottom-up is O(n). Heap sort takes O(n log n)
time. For N total items across k sorted streams, multiway merge takes
O(k + N log(k + 1)) time and O(k) working space, excluding the stored output;
list(...) additionally stores O(N) items. Ties need an explicit policy if
stable arrival order matters. In Python, equal-priority tuples may compare
their payloads, so use a suitable tie-breaker when payloads cannot be compared.
Reflect on the concept
Four fixed questions to reinforce the reasoning. Answers are not saved or scored.
