Sub topic 9
Why Heap Sort Is Not Stable
This chapter assumes you can read the sift_down and heap_sort functions from the earlier chapters. You should also be comfortable sorting records by a key, for example sorting tuples by their first field.
What stability means
A sorting algorithm is stable if records with equal keys keep the order they had in the input. Say you sort a list of orders by date, and two orders share a date. A stable sort keeps them in their original relative order. An unstable sort may swap them.
Stability matters when you sort in several passes. For example, you might sort by name and then by department, expecting names to stay alphabetical within each department. That only works if the second sort is stable. Python's built-in sorted is stable. Heap sort is not.
Where the reordering happens
Heap sort moves elements over long distances, and it does not consider where they started. Two operations cause this:
- The root-to-end swap. Each round swaps
a[0]witha[end]. The element that was atendjumps to the root and skips over everything in between, including any equal keys. - Sift-down across subtrees. Sift-down picks a child by comparing keys only. Two equal keys in different subtrees reach the root in an order set by the heap's shape, and their input order plays no part.
Neither operation tracks input positions, so equal keys can come out in any order.
A minimal counterexample
The code below is the heap sort from earlier chapters with a key parameter added, so it can sort records.
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')]
print(sorted([(2, 'a'), (2, 'b'), (1, 'c')], key=lambda r: r[0]))
# [(1, 'c'), (2, 'a'), (2, 'b')]In the input, 'a' comes before 'b'. Heap sort outputs them in reverse order. Here is the trace:
| Step | Array | What happened |
|---|---|---|
| Build heap | `(2,a) (2,b) (1,c)` | Root already ≥ children, no change |
| Swap root with index 2 | `(1,c) (2,b) (2,a)` | `(2,a)` jumps to the end |
| Sift-down, end=2 | `(2,b) (1,c) (2,a)` | `(2,b)` rises to the root |
| Swap root with index 1 | `(1,c) (2,b) (2,a)` | `(2,b)` lands before `(2,a)` |
Making it stable when you must
The usual fix is to make every key unique by adding each element's original index as a tie-breaker. If you sort by (key, index), no two keys are equal, so the output matches what a stable sort would give.
records = [(2, 'a'), (2, 'b'), (1, 'c')]
tagged = [(r[0], i, r) for i, r in enumerate(records)]
heap_sort(tagged, key=lambda t: (t[0], t[1]))
print([t[2] for t in tagged]) # [(1, 'c'), (2, 'a'), (2, 'b')]The fix costs O(n) extra space for the indices, which gives up heap sort's main selling point of O(1) extra space. If you need stability and can spend O(n) memory, merge sort or Python's sorted is usually the simpler choice.
Exercise
Trace heap_sort on [(1, 'x'), (1, 'y')] with key=lambda r: r[0]. Is the output stable?
Show answer
No. Building the heap changes nothing because the root equals its child. The loop then swaps index 0 with index 1, giving [(1, 'y'), (1, 'x')]. The input order of x and y is reversed, even on a two-element array.
Exercise
Why does the (key, index) fix produce stable output even though heap sort itself is still unstable?
Show answer
Instability only shows up when keys are equal. Adding the original index makes every composite key distinct, so there are no ties to reorder. Elements whose original keys match end up ordered by their index, which is their input order.