Building a heap in O(n), and heapsort
🌍 In real life. A teacher has a pile of 40 test papers to hand back from the highest mark down. She could sort the whole pile first. Or she could do something lazier and faster: make sure only that every small group of papers has its best one on top, then keep taking the best paper off the top and fixing the small part of the pile that changed.
That is heapsort: build a heap out of the whole list in one go, then pop from it again and again. The surprise is the first part: turning n items into a heap costs only O(n), less than pushing them in one at a time.
The idea in one sentence: to heapify a list, sift down each parent, starting from the last parent and working back to the root, so that by the time a node is fixed, both subtrees below it are already heaps; then heapsort pops the smallest n times.
Its words:
- heapify: turn a whole list into a heap in place (
heapq.heapify) - last parent: index
len(a) // 2 - 1; everything after it is a leaf, which is already a heap on its own - bottom-up: fixing the lower parents before the higher ones
- heapsort: heapify, then pop n times; the pops come out in sorted order
- in place: using the list itself, with no second list of the same size
How it works, step by step:
- the leaves (the second half of the list) are tiny heaps already
- for i from the last parent down to 0: sift
a[i]down below any smaller child - each sift-down only meets subtrees that are already heaps, so it makes the subtree rooted at i a heap
- after the root, the whole list is a heap; pop n times to sort
Watch heapify fix [9, 4, 7, 1, 8, 2, 6] from the last parent, 7, back to the root, 9:
Heapsort is that, followed by popping every item. The popped values collect in the tray in sorted order:
Why it is correct. Sift-down only works if both subtrees below the item are already heaps. Going bottom-up makes that true every time: when we reach index i, its children are higher indexes, and they were fixed earlier (or they are leaves). After sifting a[i] down, the subtree at i is a heap, and when we finish at the root, the whole list is. Starting from the root instead would sift the root into subtrees that are not heaps yet, and the result can break the rule. Heapsort then pops: each pop returns the smallest of what is left, so the pops come out in increasing order.
What it costs, by counting. Most nodes are near the bottom, and a node can only sink as far as the levels below it. In a full tree of 1,023 nodes (10 levels): 512 leaves sink 0, 256 nodes sink at most 1, 128 at most 2, and so on up to the root, at most 9. That adds up to at most 1,013 swaps, fewer than the number of nodes, so heapify is O(n). Pushing the same 1,023 values in one at a time can cost up to 8,194 swaps (each climbs as far as its depth), O(n log n). Heapsort adds n pops at O(log n) each, so it is O(n log n) in every case, in place if you build a max-heap at the front of the list. It is not stable, and in Python sorted() (Timsort, Chapter 45) is usually faster, but heapsort never slows down to O(n²).
def sift_down(a, i, n):
while True:
child = 2 * i + 1
if child >= n:
return
if child + 1 < n and a[child + 1] < a[child]:
child += 1 # the smaller child
if a[i] <= a[child]:
return
a[i], a[child] = a[child], a[i]
i = child
def heapify(a):
for i in range(len(a) // 2 - 1, -1, -1): # the last parent back to the root
sift_down(a, i, len(a))
marks = [9, 4, 7, 1, 8, 2, 6]
heapify(marks)
print(marks) # a heap: the smallest on top, the rest not sorted
import heapq
def heapsort(items):
heap = list(items) # a copy: the caller's list stays as it was
heapq.heapify(heap) # O(n)
return [heapq.heappop(heap) for _ in range(len(heap))] # n pops, O(log n) each
print(heapsort([5, 3, 8, 1, 2]))
print(heapsort([]))
def heapify_swaps(a):
a = list(a)
swaps = 0
for i in range(len(a) // 2 - 1, -1, -1):
while True:
child = 2 * i + 1
if child >= len(a):
break
if child + 1 < len(a) and a[child + 1] < a[child]:
child += 1
if a[i] <= a[child]:
break
a[i], a[child] = a[child], a[i]
swaps += 1
i = child
return swaps
print(heapify_swaps(list(range(1023, 0, -1)))) # the worst case for 1,023 valuesMistakes and edge cases.
- heapifying from the root down:
for i in range(len(a) // 2)sifts parents into subtrees that are not heaps yet; go from the last parent back to 0 - expecting heapify to sort: after
heapq.heapify(a)onlya[0]is certain to be the smallest; print it and the rest looks jumbled - sifting the leaves too: starting at
len(a) - 1works but wastes time; leaves have no children to compare with - heapsort and ties: equal values can change their order, so heapsort is not stable; use
sorted()when that matters - an empty list or one item: both are already heaps; the loop doesn't run
Quiz
What does this print?
import heapq a = [5, 3, 8, 1, 2] heapq.heapify(a) print(a, a[0])Why does heapify start at the last parent and work back to the root?
- Sift-down needs both subtrees to be heaps already, and going bottom-up makes sure they are
- The root is the hardest, so it is saved for last
- It is just a habit; any order works
Building a heap of n items with heapify, versus pushing them one at a time: which costs are right?
- heapify O(n); one at a time O(n log n)
- Both O(n log n)
- heapify O(log n); one at a time O(n)
This heapify sometimes leaves a parent bigger than its child. Which line is wrong?
def heapify(a): for i in range(len(a) // 2): sift_down(a, i, len(a))Heapsort with heapq. What does this print?
import heapq h = [7, 3, 9, 3, 1] heapq.heapify(h) print([heapq.heappop(h) for _ in range(len(h))], h)
Coding tasks
Build it yourself, without
heapq: writeheapify(a), which turns the listainto a min-heap in place by sifting down each parent from the last one back to the root. It returns nothing.Write
heapsort(items): return a new list with the items in increasing order, by heapifying a copy and popping until it is empty. Useheapq, but notsorted()or.sort(), and leave the caller's list unchanged.Count the cost. Write
heapify_swaps(a): how many swaps a bottom-up heapify of a copy ofamakes (sifting down each parent from the last one back to the root, swapping with the smaller child). The values are all different.