Sub topic 9
Stability: Which Sorts Keep Equal Keys in Their Original Order
This chapter assumes you have read the earlier chapters on bubble, selection, and insertion sort and can follow their code. It also assumes you know Python tuples and lambda functions used as sort keys.
What stability means
A sort is stable if records with equal keys come out in the same relative order they went in. Say you sort (2, 'a'), (2, 'b'), (1, 'c') by the number. A stable sort must produce (1, 'c'), (2, 'a'), (2, 'b'). The output (1, 'c'), (2, 'b'), (2, 'a') is also sorted by key, but it is not stable.
Stability only matters when records carry more data than the key. When you sort plain integers, equal values can't be told apart, so their order doesn't matter.
Why you would care
Stability lets you sort by several keys in sequence. To list employees by department, and alphabetically by name within each department, you sort by name first and then do a stable sort by department. The second sort keeps the name order inside each department. An unstable second sort would scramble it.
Checking each algorithm
The rule is simple. A sort is stable if it never moves an element past another element with an equal key.
| Algorithm | Stable? | Reason |
|---|---|---|
| Bubble sort | Yes | It swaps only adjacent pairs, and only when `a[j] > a[j + 1]`. Equal neighbors are never swapped. |
| Insertion sort | Yes | The shift loop stops at the first element that is not greater than `key`, so `key` lands after any equal elements. |
| Selection sort | No | It swaps the minimum into position `i` over a long distance. The element that was at `i` can jump past equal keys. |
Selection sort's instability, shown
def selection_sort_by_key(a, key):
n = len(a)
for i in range(n - 1):
m = i
for j in range(i + 1, n):
if key(a[j]) < key(a[m]):
m = j
if m != i:
a[i], a[m] = a[m], a[i]
return a
records = [(2, 'a'), (2, 'b'), (1, 'c')]
print(selection_sort_by_key(records, key=lambda r: r[0]))
# [(1, 'c'), (2, 'b'), (2, 'a')] -- 'a' and 'b' changed orderIn the first pass the minimum is (1, 'c') at index 2. Swapping it with index 0 sends (2, 'a') to the end, past (2, 'b').
The common error: one character breaks stability
Bubble and insertion sort are stable only because they use a strict > comparison. If you change it to >=, they move elements past their equal neighbors:
def insertion_sort_by_key(a, key, strict=True):
for i in range(1, len(a)):
item = a[i]
j = i - 1
while j >= 0 and (key(a[j]) > key(item) if strict
else key(a[j]) >= key(item)):
a[j + 1] = a[j]
j -= 1
a[j + 1] = item
return a
records = [(2, 'a'), (2, 'b'), (1, 'c')]
print(insertion_sort_by_key(list(records), lambda r: r[0]))
# [(1, 'c'), (2, 'a'), (2, 'b')] stable
print(insertion_sort_by_key(list(records), lambda r: r[0], strict=False))
# [(1, 'c'), (2, 'b'), (2, 'a')] unstableThe >= version still sorts correctly and still passes tests on plain integers. That is why this bug often goes unnoticed until someone sorts records.
Making selection sort stable
You can make selection sort stable by moving the minimum into place with a rotation instead of a swap. The elements between i and m each shift right by one position:
def stable_selection_sort(a, key):
n = len(a)
for i in range(n - 1):
m = i
for j in range(i + 1, n):
if key(a[j]) < key(a[m]):
m = j
a.insert(i, a.pop(m)) # rotate a[i..m] instead of swapping
return a
print(stable_selection_sort([(2, 'a'), (2, 'b'), (1, 'c')], lambda r: r[0]))
# [(1, 'c'), (2, 'a'), (2, 'b')]This fix costs you selection sort's main advantage. A rotation can move up to O(n) elements, so the total number of writes rises from at most n − 1 swaps to O(n²). If you need stability, insertion sort is usually the better choice.
Exercise
Bubble sort's inner comparison is changed from a[j] > a[j + 1] to a[j] >= a[j + 1]. Trace the first pass on [(1, 'x'), (1, 'y')], sorting by the number. Is the result stable, and does the early-exit check still work on input whose keys are all equal?
Show answer
On the first pass the equal keys are swapped, giving [(1, 'y'), (1, 'x')], so the sort is no longer stable. The early-exit check also breaks. Every pair of equal neighbors now causes a swap, so swapped is set on every pass. Input whose keys are all equal then takes O(n^2) work instead of one O(n) pass.
Exercise
You need to sort 50 log records by severity, and records with the same severity must keep their timestamp order. Which of the three elementary sorts can you use unchanged, and why is plain selection sort ruled out?
Show answer
You can use bubble sort or insertion sort unchanged. Both only move an element past a strictly greater one, so equal severities keep their original timestamp order. Plain selection sort is ruled out because its long-distance swap can move a record past another record with the same severity.