A priority queue
A priority queue is a waiting line where the smallest item always leaves first, whatever order items arrived in. It has two moves: push adds an item, pop removes the smallest. Python’s heapq module keeps one inside a plain list, here pq.
Read the list as a tree: item i has children at 2i + 1 and 2i + 2. heapify works from the last parent back to the root, sinking each item below its smaller child. 3 swaps put 1 on top.
heappush(pq, 2) appends 2 at the end, index 5, the next free leaf. Its parent 8 is bigger, so they swap. The new parent 1 is smaller, so 2 stops. One path, at most the tree’s height in swaps.
Popping
heappop(pq) returns pq[0], the smallest item: 1. The loop appends it to out. No search is needed, because the heap always keeps its smallest item at the root.
To fill the gap, the last item, 8, moves to the root and the list gets one shorter. 8 sinks: it swaps with its smaller child, 2, and stops at a leaf. The smallest left, 2, is on top again.
The while loop repeats until pq is empty. Each pop takes the root, moves the last item up and sinks it. Out come 2, 3, 4, 5, 8: each time, the smallest item still waiting.
Heapsort
print(out) shows [1, 2, 3, 4, 5, 8]: sorted. Build a heap, then pop every item: that is heapsort. Any priority queue sorts this way. This version fills a second list; the classic heapsort reuses the same list instead.
A push or pop moves one item along a single root-to-leaf path: at most the height, ⌊log₂ n⌋ swaps, here 2. The whole run took 8 swaps. n pops cost O(n log n); heapify only O(n). Heapsort: O(n log n).
What happens
;; step 1/8 · pq-idea priority queue: push(item), pop() -> smallest item pq = [5, 3, 8, 1, 4] a plain list is not a heap yet: 1 is not at the front heapq stores a binary min-heap inside a Python list
CPython’s heappop and heapify use a variant of sift down that makes fewer comparisons: it moves the hole all the way to a leaf, then lets the item rise back. With distinct values it ends with the same list as the swap-by-swap version drawn here. This program sorts into a second list, which costs O(n) extra memory. Classic heapsort (CLRS chapter 6, Sedgewick & Wayne §2.4) works inside one array: build a max-heap, swap the root with the last item, shrink the heap by one and sink the new root, n times.