Sub topic 6
Priority Queues and Binary Heaps
This chapter assumes you know Big-O notation and basic Python lists and tuples. It also assumes you have read the earlier chapters on edge relaxation and the greedy rule. The greedy rule says Dijkstra's algorithm must repeatedly pick the unvisited vertex with the smallest tentative distance. This chapter covers the data structure that makes that pick fast.
The Priority Queue Abstraction
A priority queue is a collection where each item has a priority. It supports two core operations:
- insert: add an item with a given priority.
- extract-min: remove and return the item with the smallest priority.
Dijkstra's algorithm needs exactly these. You insert a vertex with its tentative distance as the priority, and you extract the closest one when you are ready to expand it.
The simplest priority queue is an unsorted list. Insert takes O(1), but extract-min has to scan every item, which costs O(n). With V vertices, that adds up to O(V²) over a full run. That is acceptable for dense graphs and slow for large sparse ones. A binary heap does better.
How a Binary Heap Works
A binary min-heap is a complete binary tree in which every parent is less than or equal to its children. "Complete" means every level is full except possibly the last, which fills from left to right. Because of this shape, the tree fits in a plain array with no pointers:
- The node at index
ihas children at2*i + 1and2*i + 2. - Its parent is at
(i - 1) // 2. - The minimum is always at index 0.
Push appends the new item at the end of the array and "sifts it up." It swaps the item with its parent until the parent is no larger. Pop removes the root, moves the last item into the root's place, and "sifts it down." It swaps that item with its smaller child until both children are no smaller. Each sift moves along one root-to-leaf path, and the tree is about log₂ n levels tall.
| Operation | Unsorted list | Binary heap |
|---|---|---|
| Insert | O(1) | O(log n) |
| Extract-min | O(n) | O(log n) |
| Peek at min | O(n) | O(1) |
| Build from n items | O(n) | O(n) with heapify |
Python's heapq Module
Python has no heap class. Instead, the heapq module provides functions that treat an ordinary list as a min-heap.
import heapq
heap = []
heapq.heappush(heap, (5, "D"))
heapq.heappush(heap, (1, "C"))
heapq.heappush(heap, (4, "B"))
heapq.heappush(heap, (3, "B"))
print(heap[0]) # (1, 'C') -- peek without removing
while heap:
print(heapq.heappop(heap))
# (1, 'C')
# (3, 'B')
# (4, 'B')
# (5, 'D')
items = [(7, "X"), (2, "Y"), (6, "Z")]
heapq.heapify(items) # rearranges in place, O(n)
print(items[0]) # (2, 'Y')The example stores (distance, node) tuples. Python compares tuples element by element, so the distance decides the order. The node label only matters when two distances tie.
The Missing Operation
Note that vertex "B" appears twice in the example above, with priorities 3 and 4. heapq cannot find an item inside the heap and lower its priority. That operation is called decrease-key, and supporting it requires tracking each item's position in the array. Dijkstra's algorithm lowers distances often, so the usual Python approach is to push a new entry and ignore the outdated one when it is popped later. The next chapter builds the algorithm on this pattern.
Exercise
In the heap array [1, 3, 4, 5, 9, 8], you push the value 2. Show the array after the sift-up finishes.
Show answer
The 2 is appended at index 6. Its parent is at index (6-1)//2 = 2, which holds 4. Since 2 < 4, they swap, so 2 moves to index 2. The new parent is at index 0, which holds 1. Since 1 < 2, the sift-up stops. The result is [1, 3, 2, 5, 9, 8, 4].
Exercise
Why does Dijkstra's algorithm push (distance, node) tuples instead of (node, distance)?
Show answer
heapq orders tuples by their first element. Putting the distance first makes the heap pop the vertex with the smallest tentative distance, which is what the greedy rule requires. Putting the node first would order vertices by their labels.