Sub topic 9
Stability: Which Sorts Keep Equal Keys in Their Original Order
This chapter assumes you can already read and trace the in-place versions of bubble sort, selection sort, and insertion sort from earlier chapters. It also assumes you are comfortable with Python lists, tuples, and lambda key functions. The question here is narrow but practical. When two records compare as equal, does the sort leave them in the order they arrived?
What Stability Means
A sort is stable if any two elements with equal keys keep their relative order from the input. The key is the part of each record the sort compares. The rest of the record goes along with it.
Stability only matters when equal keys can be told apart. Sorting the plain integers [3, 1, 3] gives [1, 3, 3] either way, because one 3 looks exactly like the other. Sorting records such as (age, name) by age is different. Two people aged 30 are equal under the comparison but are different records, so their final order is visible.
The formal condition is this. Take any input positions p < q with key(a[p]) == key(a[q]). After a stable sort, the element that started at p still comes before the element that started at q.
Why You Would Want It
The main use of stability is sorting by several keys in passes. Suppose you want employees ordered by department, and alphabetically by name within each department. With a stable sort you can do it in two passes:
- Sort by the secondary key (name).
- Stable-sort by the primary key (department).
The second pass groups records by department. Because it is stable, it keeps the name order from the first pass inside each group. An unstable second pass can scramble the names inside a department, and the first pass is wasted.
Stability also matters when the input order carries meaning that the key does not capture: arrival time in a queue, insertion order in a UI list, or an earlier sort the user already applied by clicking a column header.
Bubble Sort Is Stable
Bubble sort only ever swaps adjacent elements, and only when the left one is strictly greater than the right one. Two equal elements never satisfy a[j] > a[j + 1], so a pass never swaps them directly.
Could they pass each other indirectly? No. For two elements to change relative order, at some moment they must be neighbors and get swapped. A sort that moves elements only by adjacent swaps can reorder a pair only by swapping that pair while they are next to each other. Bubble sort refuses to make that swap when the keys are equal, so equal elements keep their order.
The proof depends on the strict comparison. If you write a[j] >= a[j + 1], the sort still produces sorted output, but now it swaps every adjacent equal pair it meets, and stability is lost.
Insertion Sort Is Stable
Insertion sort takes key = a[i] and shifts elements of the sorted prefix to the right while they are strictly greater than the key. It stops at the first element that is less than or equal to the key and drops the key just after it.
Every equal element that came earlier in the input is already in the prefix. The scan stops when it reaches the rightmost of those equal elements, so the key lands after all of them. Equal elements that come later in the input have not been processed yet. They will in turn land after this key. Relative order among equal keys is preserved at every step.
Change the loop condition to a[j] >= key and the scan walks past equal elements. The key lands in front of them, which reverses their order. The output is still sorted, so normal tests on integer lists will not catch the bug.
Selection Sort Is Not Stable
Selection sort finds the minimum of the unsorted suffix and swaps it into position i. That swap can move two elements a long distance at once. The element that was sitting at position i jumps forward to wherever the minimum was, possibly past an element with the same key.
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 orderOn the first pass the minimum is (1, 'c') at index 2. Swapping it with index 0 sends (2, 'a') to index 2, which jumps it over (2, 'b'). No later pass repairs this, because the two 2s compare as equal.
Using strict < when picking the minimum does not fix this. Strict < makes the sort choose the first of several equal minimums, which is correct for the element being placed. The damage happens to the element being displaced, and the comparison operator has no control over where that element goes.
Making Selection Sort Stable
You can make selection sort stable by replacing the swap with a rotation. Remove the minimum, shift the elements between i and m one place right, and put the minimum at i. Nothing jumps over anything.
def stable_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
item = a[m]
while m > i:
a[m] = a[m - 1]
m -= 1
a[i] = item
return a
records = [(2, 'a'), (2, 'b'), (1, 'c')]
print(stable_selection_sort_by_key(records, key=lambda r: r[0]))
# [(1, 'c'), (2, 'a'), (2, 'b')]This fix removes the main reason to choose selection sort. The swap version does at most n - 1 swaps. The rotating version can do Θ(n²) element writes in the worst case, the same order as insertion sort, and it still makes all n(n - 1)/2 comparisons. A linked-list version can unlink the minimum and relink it in O(1) time, so it is stable without extra writes. For arrays, you choose between stability and few writes.
Testing Stability Mechanically
To test stability, tag each record with its original index. Then sort by the real key only and check that tagged indices increase within every run of equal keys. The harness below runs all the variants on the same input. Each sort takes a key function and sorts in place.
def bubble_sort_by_key(a, key):
n = len(a)
for i in range(n - 1):
swapped = False
for j in range(n - 1 - i):
if key(a[j]) > key(a[j + 1]):
a[j], a[j + 1] = a[j + 1], a[j]
swapped = True
if not swapped:
break
return a
def insertion_sort_by_key(a, key):
for i in range(1, len(a)):
item = a[i]
j = i - 1
while j >= 0 and key(a[j]) > key(item):
a[j + 1] = a[j]
j -= 1
a[j + 1] = item
return a
def insertion_sort_ge_by_key(a, key):
# Bug: >= walks past equal keys.
for i in range(1, len(a)):
item = a[i]
j = i - 1
while j >= 0 and key(a[j]) >= key(item):
a[j + 1] = a[j]
j -= 1
a[j + 1] = item
return a
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
def stable_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
item = a[m]
while m > i:
a[m] = a[m - 1]
m -= 1
a[i] = item
return a
def is_stable_on(sort_fn, records, key):
tagged = [(r, idx) for idx, r in enumerate(records)]
result = sort_fn(tagged, key=lambda t: key(t[0]))
for (r1, i1), (r2, i2) in zip(result, result[1:]):
if key(r1) == key(r2) and i1 > i2:
return False
return True
records = [(2, 'a'), (2, 'b'), (1, 'c')]
k = lambda r: r[0]
for fn in [bubble_sort_by_key, insertion_sort_by_key, insertion_sort_ge_by_key,
selection_sort_by_key, stable_selection_sort_by_key]:
print(f"{fn.__name__:30} stable here: {is_stable_on(fn, records, k)}")
# bubble_sort_by_key stable here: True
# insertion_sort_by_key stable here: True
# insertion_sort_ge_by_key stable here: False
# selection_sort_by_key stable here: False
# stable_selection_sort_by_key stable here: TrueA False result is a proof of instability. A True result only says this input did not expose a problem. For real confidence, run the check on many random inputs with a small key range, such as keys drawn from 0..2, so equal keys show up often.
The Decorate Trick
Any sort, stable or not, gives a stable result if you compare on (key, original_index) instead of key. No two of these pairs are equal, so there are no ties left to break. The cost is O(n) extra space for the indices and a slightly more expensive comparison. That gives up the "in place, O(1) extra space" property these elementary sorts are usually chosen for, but it is a valid option when you need a stable result from an unstable routine.
Summary Table
| Algorithm | Stable? | Reason | What breaks or fixes it |
|---|---|---|---|
| Bubble sort | Yes | Only adjacent swaps, only on strict `>` | Using `>=` makes it unstable |
| Insertion sort | Yes | Shifts stop at the first element `<=` the key | Using `>=` in the shift loop makes it unstable |
| Selection sort (swap) | No | Long-distance swap moves the displaced element past equal keys | Rotation instead of swap makes it stable but costs Θ(n²) writes |
| Selection sort (linked list) | Yes | Unlinking and relinking moves nothing else | Only possible on linked structures |
Exercise
Starting from [(3,'x'), (1,'y'), (3,'z'), (1,'w')] sorted by the first field, trace the swap-based selection sort and give the final list. Is the result stable on this input?
Show answer
Pass 0: the minimum is (1,'y') at index 1; swap with index 0 to get [(1,'y'), (3,'x'), (3,'z'), (1,'w')]. Pass 1: the minimum of indices 1..3 is (1,'w') at index 3; swap with index 1 to get [(1,'y'), (1,'w'), (3,'z'), (3,'x')]. Pass 2: indices 2..3 hold equal keys, so no swap. The final list is [(1,'y'), (1,'w'), (3,'z'), (3,'x')]. The 1s are in input order, but (3,'z') now comes before (3,'x'), so the result is unstable.
Exercise
A colleague changes bubble sort's comparison from a[j] > a[j+1] to a[j] >= a[j+1] "to be safe". The output on integer test lists is still sorted. What has changed, and what other cost does the change add?
Show answer
The sort is no longer stable, because it now swaps adjacent equal records and reverses their order. It also does extra swaps on every equal pair. Worse, the early-exit check never sees a swap-free pass when the input contains adjacent equal keys, so on already sorted input with duplicates the sort loses its O(n) best case.
Exercise
You need to sort log entries by severity, keeping entries of the same severity in timestamp order. They already arrive in timestamp order. Which of the three elementary sorts can you use directly, and why not the other one?
Show answer
Bubble sort or insertion sort, written with strict comparisons. Both are stable, so a single pass by severity keeps the timestamp order within each severity level. Swap-based selection sort is unstable and could reorder entries that share a severity, unless you switch to the rotating variant or sort on (severity, original index).