Heaps and Priority Queues: heapq, Top-k and Heap Sort
Many programs repeatedly need "the most urgent item next": the next event in a simulation, the closest unvisited vertex in a shortest-path search, the smallest of k sorted streams being merged. A binary heap answers that question in O(1) and absorbs each change in O(log n), using nothing more than a plain array. Examples use Python 3.10 or later and only the standard library.
A priority queue is an interface
A priority queue stores items with priorities and supports three operations: insert an item, look at the item with the smallest priority, and remove that item. (A max-priority queue does the same with the largest.) It says nothing about how the items are stored. A sorted list makes removal cheap but insertion O(n); an unsorted list makes insertion cheap but finding the minimum O(n). A binary heap makes all three operations fast, which is why it is the usual implementation.
The binary heap
A binary min-heap is a binary tree with two properties:
- Shape: it is a complete tree, every level full except possibly the last, which fills from the left. A complete tree with n nodes has height floor(log2 n).
- Heap order: every node's key is less than or equal to the keys of its children. So the smallest key is at the root. Nothing is said about the order between siblings or cousins; a heap is not sorted.
Because the tree is complete, it fits in an array with no pointers at all. Store the levels left to right; then for the node at index i (counting from 0), the children are at 2*i + 1 and 2*i + 2, and the parent is at (i - 1) // 2. Python's heapq module uses exactly this layout on an ordinary list:
import heapq
h = []
for x in [9, 4, 7, 1, 8, 2]:
heapq.heappush(h, x) # O(log n) each
print("array:", h)
for i, x in enumerate(h):
kids = [h[c] for c in (2 * i + 1, 2 * i + 2) if c < len(h)]
parent = h[(i - 1) // 2] if i > 0 else None
print(f"index {i}: value {x}, parent {parent}, children {kids}")
print("peek:", h[0]) # O(1): the minimum is always at index 0
print("pops:", [heapq.heappop(h) for _ in range(3)]) # O(log n) each
print("left:", h)
array: [1, 4, 2, 9, 8, 7]
index 0: value 1, parent None, children [4, 2]
index 1: value 4, parent 1, children [9, 8]
index 2: value 2, parent 1, children [7]
index 3: value 9, parent 4, children []
index 4: value 8, parent 4, children []
index 5: value 7, parent 2, children []
peek: 1
pops: [1, 2, 4]
left: [7, 8, 9]
Every parent is at most its children (1 over 4 and 2, 4 over 9 and 8, 2 over 7), yet the array as a whole is not sorted.
Push, pop and peek
- Peek reads index 0: O(1).
- Push appends the new item at the end (keeping the shape) and then sifts it up: while it is smaller than its parent, swap the two. It can climb at most the height of the tree, so push is O(log n).
- Pop removes the root, moves the last item into its place and sifts it down: while it is larger than its smaller child, swap with that child. Again at most the height: O(log n).
Building a heap in O(n)
Pushing n items one by one costs O(n log n). heapq.heapify does better by working bottom-up: it sifts down every non-leaf node, starting from the last one and ending at the root. Half the nodes are leaves and need no work; a quarter sit one level up and can move down at most one level; an eighth can move at most two, and so on. The sum n/4 x 1 + n/8 x 2 + n/16 x 3 + ... stays below n, so building a heap is O(n). Counting the swaps on reversed input, which forces many of them, shows the linear growth:
def count_heapify(a): # bottom-up construction, counts swaps
swaps, n = 0, len(a)
for start in range(n // 2 - 1, -1, -1):
root = start
while 2 * root + 1 < n:
child = 2 * root + 1
if child + 1 < n and a[child + 1] < a[child]:
child += 1
if a[root] <= a[child]:
break
a[root], a[child] = a[child], a[root]
swaps += 1
root = child
return swaps
for n in [1000, 10000, 100000]:
a = list(range(n, 0, -1)) # reversed input: many swaps for a min-heap
swaps = count_heapify(a)
assert all(a[(i - 1) // 2] <= a[i] for i in range(1, n)) # it is a heap
print(f"n = {n:6}: {swaps:6} swaps, {swaps / n:.2f} per item")
n = 1000: 992 swaps, 0.99 per item
n = 10000: 9992 swaps, 1.00 per item
n = 100000: 99990 swaps, 1.00 per item
About one swap per item at every size, where pushing one at a time can cost up to log2 n swaps per item. Use heapify whenever all the items are available up front.
Python's heapq in practice
heapq provides a min-heap only. Two habits cover most real uses:
- For a max-heap of numbers, push negated keys and negate again when you pop.
- For a priority queue of arbitrary items, push tuples
(priority, counter, item). Tuples compare element by element, so when two priorities are equal Python would go on to compare the items themselves, which fails withTypeErrorfor types such as dicts and can give an arbitrary order otherwise. A strictly increasing counter fromitertools.count()settles every tie, and also makes equal priorities come out in insertion order.
import heapq
import itertools
# A max-heap of numbers: store negated keys.
scores = [40, 95, 70, 85]
max_heap = [-s for s in scores]
heapq.heapify(max_heap) # O(n)
print("largest:", -heapq.heappop(max_heap))
# A priority queue of tasks: (priority, counter, item).
# The counter breaks ties, so two items are never compared directly.
counter = itertools.count()
tasks = []
for priority, task in [(2, {"name": "email"}), (1, {"name": "backup"}),
(2, {"name": "report"}), (3, {"name": "cleanup"})]:
heapq.heappush(tasks, (priority, next(counter), task))
while tasks:
priority, _, task = heapq.heappop(tasks)
print(priority, task["name"])
largest: 95
1 backup
2 email
2 report
3 cleanup
This tuple pattern is what a shortest-path search keeps in its heap, with the distance so far as the priority; Dijkstra's algorithm is built on it.
Top-k problems
To find the k largest of n items, sorting everything costs O(n log n). A min-heap of size k does it in O(n log k) time and O(k) extra space: keep the k largest seen so far, with the smallest of them at the root, and replace the root whenever a bigger item arrives. When k is much smaller than n, that is close to a single pass. heapq.nlargest and heapq.nsmallest wrap up the same idea:
import heapq
import random
random.seed(7)
data = [random.randint(1, 1000) for _ in range(20)]
def top_k(items, k): # O(n log k) time, O(k) extra space
heap = [] # min-heap of the k largest seen so far
for x in items:
if len(heap) < k:
heapq.heappush(heap, x)
elif x > heap[0]:
heapq.heapreplace(heap, x) # pop the smallest, push x
return sorted(heap, reverse=True)
print(data)
print(top_k(data, 3))
print(heapq.nlargest(3, data))
print(sorted(data, reverse=True)[:3])
[332, 971, 155, 405, 667, 50, 75, 841, 549, 97, 375, 597, 60, 932, 520, 220, 39, 89, 445, 429]
[971, 932, 841]
[971, 932, 841]
[971, 932, 841]
All three methods agree. For k = 1, use max; when k is close to n, sorting is simpler.
Heap sort
Heap sort turns the heap into an in-place sorting algorithm. Build a max-heap in the array in O(n). Then repeat n - 1 times: swap the root (the largest remaining item) with the last item of the heap, shrink the heap by one so that item stays in its final position, and sift the new root down in O(log n).
def sift_down(a, start, end, key):
"""Move a[start] down until the max-heap property holds in a[start:end]."""
root = start
while True:
child = 2 * root + 1
if child >= end:
return
if child + 1 < end and key(a[child + 1]) > key(a[child]):
child += 1 # pick the larger child
if key(a[root]) >= key(a[child]):
return
a[root], a[child] = a[child], a[root]
root = child
def heap_sort(a, key=lambda x: x):
n = len(a)
for start in range(n // 2 - 1, -1, -1): # build a max-heap: O(n)
sift_down(a, start, n, key)
for end in range(n - 1, 0, -1): # n - 1 extractions: O(n log n)
a[0], a[end] = a[end], a[0] # move the max to its final place
sift_down(a, 0, end, key)
nums = [5, 2, 9, 1, 5, 6, 3]
heap_sort(nums)
print(nums)
cards = [(3, "a"), (1, "b"), (3, "c"), (2, "d")]
heap_sort(cards, key=lambda card: card[0]) # sort by number only
print(cards)
[1, 2, 3, 5, 5, 6, 9]
[(1, 'b'), (2, 'd'), (3, 'c'), (3, 'a')]
Heap sort runs in O(n log n) in the worst case and needs only O(1) extra space, a combination merge sort (O(n) extra space for arrays) and quicksort (O(n^2) worst case) do not provide. It is not stable: the second run sorts by the number alone, and the two cards with key 3 come out as c before a, the reverse of their input order, because the swaps carry items far across the array. In practice it is often slower than a good quicksort because its jumps between parent and child indices make poor use of the processor cache, which is one reason libraries tend to use it as a fallback rather than as their main sort.
The Algorithm Comparison Tool lists heap sort as O(n log n) in the best, average and worst case, with O(1) space and not stable. The best case there assumes distinct keys; when all keys are equal, every sift-down stops at once and the sort finishes in O(n).
J. W. J. Williams described heap sort, and with it the binary heap, in 1964 in the Communications of the ACM; Robert W. Floyd published an improved version the same year.
Check yourself
- In a min-heap stored in an array, where is the largest item? (Somewhere among the leaves, roughly the second half of the array; a heap gives no fast way to find it.)
- Why push
(priority, counter, item)instead of(priority, item)? (Equal priorities would compare the items, which may be impossible or meaningless.) - What is the cost of finding the 10 largest of a million numbers with a size-10 heap? (O(n log 10), effectively one pass over the data.)