Sub topic 3
Why Heap Sort Is Not Stable
This chapter assumes you can already write sift_down, build_max_heap, and heap_sort, and that you know Big-O notation.
Stability
A sort is stable if records with equal keys keep their original order. Heap sort is not stable. Its long-distance swaps, root to end and parent to child, move equal keys past each other without checking where they started.
def sift_down(a, start, end, key):
root = start
while True:
child = 2 * root + 1
if child >= end:
break
if child + 1 < end and key(a[child + 1]) > key(a[child]):
child += 1
if key(a[root]) >= key(a[child]):
break
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):
sift_down(a, start, n, key)
for end in range(n - 1, 0, -1):
a[0], a[end] = a[end], a[0]
sift_down(a, 0, end, key)
records = [(2, "a"), (2, "b"), (1, "c")]
heap_sort(records, key=lambda r: r[0])
print(records) # [(1, 'c'), (2, 'b'), (2, 'a')]Record "a" came before "b" in the input, but the first root-to-end swap sent "a" to the last position.
Why Building a Heap Is O(n)
At most ⌈n / 2^(h+1)⌉ nodes have height h, and sifting one of them down costs O(h). The total work is n · Σ h / 2^(h+1). That series converges to 1, so the total is O(n). Most nodes sit near the leaves, where sifting is cheap.
Sorting with heapq
Python's heapq module is a min-heap. To get a stable result, add the original index as a tiebreaker:
import heapq
def stable_heapq_sort(items, key):
h = [(key(x), i, x) for i, x in enumerate(items)]
heapq.heapify(h)
return [heapq.heappop(h)[2] for _ in range(len(h))]
print(stable_heapq_sort([(2, "a"), (2, "b"), (1, "c")], key=lambda r: r[0]))
# [(1, 'c'), (2, 'a'), (2, 'b')]This version uses O(n) extra memory. If you only need the k smallest items, heapq.nsmallest(k, items) is the simpler choice.
Comparison with Other Sorts
| Sort | Worst-case time | Extra space | Stable | Cache behavior |
|---|---|---|---|---|
| Heap sort | O(n log n) | O(1) | No | Poor |
| Quicksort | O(n²) | O(log n) | No | Good |
| Merge sort | O(n log n) | O(n) | Yes | Good |
In practice quicksort is usually faster. Heap sort is the one to pick when you need a guaranteed worst case and no extra memory.
The Introsort Fallback
Introsort starts with quicksort. If the recursion depth goes past about 2·log₂ n, it switches to heap sort for that part of the array, which caps the worst case at O(n log n). C++ std::sort implementations use this design.
Variants
- Bottom-up heap sort follows the larger child all the way down to a leaf, then sifts the element back up. This cuts comparisons from about 2n log₂ n to about n log₂ n + O(n).
- d-ary heaps give each node d children, so the tree has height log_d n. Each level then costs d − 1 comparisons, but the shallower tree often makes better use of the cache.
Exercise
Why does adding the original index to each heapq tuple make the sort stable?
Show answer
When two keys are equal, tuple comparison moves on to the index, and the earlier index is smaller. Equal keys therefore pop in their original order.
Exercise
Why does introsort fall back to heap sort rather than merge sort?
Show answer
Heap sort keeps the O(n log n) worst-case guarantee while sorting in place with O(1) extra space. Merge sort would need O(n) extra memory.