Sub topic 9
Why Heap Sort Is Not Stable
Earlier chapters showed that heap sort runs in O(n log n) time in every case and needs only O(1) extra space. It also has a weakness that matters whenever you sort records instead of plain numbers: heap sort is not stable. This chapter explains what stability means, shows heap sort breaking it on very small inputs, identifies the steps that cause it, and shows how to get a stable result when you need one.
This chapter assumes you have the sift_down, build_max_heap, and heap_sort functions from the previous chapters. You should also be comfortable with Python tuples and key functions.
What Stability Means
A sorting algorithm is stable if two elements with equal keys come out in the same relative order they had going in. The key is the value you sort by. If record A appears before record B in the input and both have the same key, a stable sort guarantees that A still appears before B in the output.
Stability is invisible when you sort plain integers, because two equal integers cannot be told apart. It becomes visible when each element carries more data than its key:
| Input position | Name | Department (key) |
|---|---|---|
| 0 | Ana | 2 |
| 1 | Ben | 1 |
| 2 | Cleo | 2 |
| 3 | Dev | 1 |
A stable sort by department must produce Ben, Dev, Ana, Cleo. Ben stays before Dev and Ana stays before Cleo, because that was their order in the input. An unstable sort may also produce Dev, Ben, Cleo, Ana. Both outputs are correctly sorted by department. Only the first is stable.
Why you would care
- Multi-pass sorting. To sort by department and then by name within each department, a common method is to sort by name first and then do a stable sort by department. An unstable second pass throws away the name ordering.
- Preserving meaningful input order. If the input is already ordered by arrival time, a stable sort by priority keeps earlier arrivals ahead of later ones that have the same priority.
- Reproducible output. With an unstable sort, tied records can come out in an order that depends on what else is in the array. That makes diffs, tests, and paginated results harder to reason about.
A Key-Aware Heap Sort
To watch stability fail, the sort has to handle records. The version below is the same algorithm as before, with every comparison going through a key function. Its behavior on ties is the same as the integer version: sift_down moves to the right child only when that child is strictly larger, and it stops when the parent is greater than or equal to the chosen child.
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 build_max_heap(a, key):
n = len(a)
for start in range(n // 2 - 1, -1, -1):
sift_down(a, start, n, key)
def heap_sort(a, key=lambda x: x):
build_max_heap(a, key)
for end in range(len(a) - 1, 0, -1):
a[0], a[end] = a[end], a[0]
sift_down(a, 0, end, key)
pair = [(1, "a"), (1, "b")]
heap_sort(pair, key=lambda r: r[0])
print(pair) # [(1, 'b'), (1, 'a')]
triple = [(2, "a"), (2, "b"), (1, "c")]
heap_sort(triple, key=lambda r: r[0])
print(triple) # [(1, 'c'), (2, 'b'), (2, 'a')]Two equal elements are enough to show the problem. The input has a before b, and the output has b before a.
Tracing the Failure
The two-element case
- Build. With n = 2, the only non-leaf is index 0. Its child
(1, "b")is not larger, because1 >= 1, sosift_downstops immediately. The array is unchanged:[(1,a), (1,b)]. - Extract. With
end = 1, swap index 0 and index 1, which gives[(1,b), (1,a)]. The heap now has size 1, so there is nothing left to sift.
The extraction step reversed the two equal elements. Heap sort always moves the current root to the last unsorted position. When the root ties with something that sits after it, that swap jumps the root over it.
The three-element case
Step by step:
- Build. At index 0, the children are
2band1c. The left child2bis chosen, and2 >= 2stops the sift. The heap is[2a, 2b, 1c]. - First extraction. Swap
2afrom the root to index 2. That locks2ainto the last position, which in the final output means it comes after every other 2. - Sift. The new root
1cis smaller than2b, so they swap:[2b, 1c, 2a]. - Second extraction.
2bgoes to index 1. The final array is[1c, 2b, 2a].
Element 2a came first in the input, so it was at the root and was extracted first. Extracting first means landing furthest to the right. For tied keys, heap sort tends to reverse the order of whichever tied elements reach the root first.
Where the Instability Comes From
The problem has more than one source. Three parts of the algorithm each move elements across long distances without regard to their original order.
1. The root-to-end swap
Every extraction swaps index 0 with index end. The element that was at end jumps to the front, past everything in between. Any equal element in that range now sits behind it, which is a reversal. Swaps between distant positions break stability in general. Selection sort is unstable for the same reason.
2. Sift-down follows tree paths, not array order
A sift moves an element from index i to 2i + 1 or 2i + 2. It leaps over every element between those positions. Two equal keys in different subtrees have no ordering relationship in a heap, so whichever one gets promoted first depends on the tree's shape. Their input positions play no part.
3. The heap is only a partial order
The max-heap property orders each parent with its children. It says nothing about siblings or cousins. After build_max_heap, an element's array index no longer tells you where it was in the input. Once that information is lost, no later step can restore it.
Getting a Stable Result
The standard fix is to decorate each element with its original index and sort by the pair (key, index). After decoration no two elements compare as equal. A sort with no ties produces exactly one correct order, and stability only ever affects ties. That one correct order is therefore the stable order.
def stable_heap_sort(records, key=lambda x: x):
decorated = [(key(r), i, r) for i, r in enumerate(records)]
heap_sort(decorated, key=lambda t: (t[0], t[1]))
return [t[2] for t in decorated]
staff = [("Ana", 2), ("Ben", 1), ("Cleo", 2), ("Dev", 1)]
print(stable_heap_sort(staff, key=lambda r: r[1]))
# [('Ben', 1), ('Dev', 1), ('Ana', 2), ('Cleo', 2)]This code reuses the key-aware heap_sort from earlier in the chapter. The key passed to it returns only (key, index), so the record itself is never compared. That matters when records do not support <, such as dictionaries or objects without ordering methods.
What decoration costs
| Property | Plain heap sort | Decorated heap sort |
|---|---|---|
| Stable | No | Yes |
| Time | O(n log n) | O(n log n), with somewhat costlier comparisons |
| Extra space | O(1) | O(n) for the decorated list |
| In place | Yes | No |
Decoration removes heap sort's main advantage, which is O(1) extra space. If you can afford O(n) extra memory and need stability, merge sort or Python's built-in sorted (Timsort, which is stable) is usually faster and simpler. Use decoration when you specifically need heap behavior. A common example is a priority queue built on heapq, where (priority, counter, item) entries keep equal-priority items in first-in, first-out order.
Common Mistakes
- Testing stability with plain integers.
heap_sort([3, 1, 3])looks correct because the two 3s cannot be told apart. Always test with records that have tied keys and distinguishable payloads. - Assuming "nearly stable" behavior. Heap sort has no reliable pattern on ties. Depending on the array's shape, tied elements may come out reversed, scrambled, or occasionally in order.
- Decorating without the index. Sorting
(key, record)tuples breaks ties by comparing records. That gives an order based on record contents instead of input order, and it raisesTypeErrorif the records cannot be compared.
Exercises
Exercise
Using the integer-style heapsort from the earlier chapters (no key changes), label four equal values x0, x1, x2, x3 by input position and run heap sort on them. In what order do they come out, and does siftdown ever swap?
Show answer
The build phase changes nothing because every parent is >= its children. Extraction swaps the root with index 3 to give [x3, x1, x2, x0], then with index 2 to give [x2, x1, x3, x0], then with index 1 to give [x1, x2, x3, x0]. Sift-down never swaps because the >= test always stops it. The output x1, x2, x3, x0 is not the input order, so the root-to-end swaps alone are enough to break stability.
Exercise
A colleague says that changing the stop test in sift_down from >= to > makes heap sort stable. Give a reason or a counterexample showing this is wrong.
Show answer
With >, a parent that ties with its child swaps downward, which adds more movement between equal keys instead of preventing it. The two-element input [(1,a), (1,b)] still has its root swapped to the end during extraction. Build would swap the two elements, and then extraction would swap them back, so this input happens to end in order. Larger inputs such as the all-equal array still come out scrambled. No tie-break rule removes the root-to-end swap, so the algorithm stays unstable.
Exercise
You must sort 10 million log records by severity, keep arrival order within each severity, and you have plenty of memory. Should you use stableheapsort? Explain.
Show answer
Usually not. Stability requires O(n) extra space either way, and with that memory available, Python's sorted(records, key=...) is stable, runs in O(n log n) time, is implemented in C, and benefits from any existing order in the data. Decorated heap sort gives the same guarantee more slowly. Keep heap-based approaches for cases that need heap operations, such as streaming top-k selection or priority queues.