Sub topic 6
Which Classic Algorithms Are Stable, and Why
This chapter assumes you already know what a stable sort is: it keeps elements with equal keys in their original relative order. It also assumes you can read Python and know Big-O notation. The goal is to explain why each classic algorithm is or is not stable, by looking at how it moves elements. Once you know which kinds of moves break stability, you can judge an algorithm you haven't seen before by reading its code.
The rule: watch how elements move
Every comparison sort rearranges elements by some combination of moves. Stability depends on one question:
Can a step ever move an element past another element with an equal key?
If no step can do that, the algorithm is stable. If even one step can, the algorithm is unstable, even if many inputs happen to come out in the right order.
Two kinds of moves are safe:
- Swapping adjacent elements only when the left key is strictly greater. Equal neighbours are never swapped, so they never change places.
- Merging two ordered sequences and taking from the left sequence on ties. Everything in the left sequence came earlier in the input, so ties are settled in input order.
One kind of move is dangerous:
- Long-distance swaps. If element
xat position 2 jumps to position 9, it passes everything in positions 3 to 8. Any of those with a key equal toxnow has its order reversed relative tox.
Stable algorithms
Insertion sort
Insertion sort takes each element in turn and shifts it left past every element with a strictly greater key. This is the version from earlier in the tutorial:
def insertion_sort(items, key):
for i in range(1, len(items)):
current = items[i]
j = i - 1
# Strict '>' never moves an element past an equal one, which keeps the sort stable.
while j >= 0 and key(items[j]) > key(current):
items[j + 1] = items[j]
j -= 1
items[j + 1] = current
return items
print(insertion_sort([(2, "a"), (1, "b"), (2, "c")], key=lambda r: r[0]))
# [(1, 'b'), (2, 'a'), (2, 'c')]The shifting loop stops as soon as it meets a key that is less than or equal to the current one. So current lands just after any earlier equal element and never passes it. If you change > to >=, the loop walks past equal elements and the sort becomes unstable. It still sorts correctly. That one-character bug is a common way a stable algorithm turns unstable while every correctness test still passes.
Bubble sort
Bubble sort repeatedly passes over the list and swaps adjacent pairs that are out of order. With the condition key(a[j]) > key(a[j + 1]), equal neighbours are never swapped, so it is stable for the same reason insertion sort is. With >= it is unstable, and it also does pointless work.
Merge sort
Merge sort splits the list in half, sorts each half recursively, and merges the two sorted halves. The split is stable automatically: the left half holds exactly the elements that came first in the input. Stability then depends entirely on how the merge settles ties.
def merge_sort(items, key):
if len(items) <= 1:
return list(items)
mid = len(items) // 2
left = merge_sort(items[:mid], key)
right = merge_sort(items[mid:], key)
out = []
i = j = 0
while i < len(left) and j < len(right):
# '<=' takes from the left half on ties, so earlier input stays earlier.
if key(left[i]) <= key(right[j]):
out.append(left[i])
i += 1
else:
out.append(right[j])
j += 1
out.extend(left[i:])
out.extend(right[j:])
return out
data = [(3, "a"), (1, "b"), (3, "c"), (1, "d")]
print(merge_sort(data, key=lambda r: r[0]))
# [(1, 'b'), (1, 'd'), (3, 'a'), (3, 'c')]If you write < in the merge, ties are taken from the right half, which reverses equal elements across the split. The cost of merge sort's stability is the buffer: the textbook version needs O(n) extra memory to hold the merged output. In-place stable merges exist, but they are complicated and slower in practice. That memory cost is why many libraries offer an unstable sort as well.
Counting sort and radix sort
Counting sort is not a comparison sort, but it matters here because radix sort depends on it being stable. After counting how many times each key occurs and turning the counts into end positions, it places elements by walking the input backwards:
def counting_sort(items, key, max_key):
counts = [0] * (max_key + 1)
for item in items:
counts[key(item)] += 1
for k in range(1, max_key + 1):
counts[k] += counts[k - 1] # counts[k] is now one past the last slot for key k
out = [None] * len(items)
for item in reversed(items): # backwards walk fills each key's slots from the end
counts[key(item)] -= 1
out[counts[key(item)]] = item
return out
print(counting_sort([(2, "a"), (0, "b"), (2, "c")], key=lambda r: r[0], max_key=2))
# [(0, 'b'), (2, 'a'), (2, 'c')]The last element with a given key goes into that key's last slot, so equal keys keep their input order. If you walk forwards with the same end positions, equal keys come out reversed. Least-significant-digit radix sort runs counting sort once per digit. It gives correct results only because each pass keeps the order set by the earlier passes. This is the same idea as multi-key sorting with successive stable sorts.
Unstable algorithms
Selection sort
Selection sort finds the minimum of the unsorted part and swaps it into the front position. The swap is the problem. Take [(2, "a"), (2, "b"), (1, "c")]. The minimum (1, "c") is swapped with (2, "a") at the front, which gives [(1, "c"), (2, "b"), (2, "a")]. "a" jumped from the front to the end, past "b", and nothing later puts them back. You can make selection sort stable by shifting the block right instead of swapping. That turns each step into an O(n) move, and the result is basically insertion sort done backwards.
Quicksort
Quicksort partitions the list around a pivot and recurses on each side. Common partition schemes (Lomuto, Hoare) swap elements across long distances, so equal keys get scrambled. The scrambling is easy to miss: on small inputs the recursion often swaps two equal elements back into place by accident. You need a slightly larger example to see it:
def quicksort(items, key, lo=0, hi=None):
if hi is None:
hi = len(items) - 1
if lo >= hi:
return items
pivot = key(items[hi]) # Lomuto: last element is the pivot
i = lo
for j in range(lo, hi):
if key(items[j]) < pivot:
items[i], items[j] = items[j], items[i]
i += 1
items[i], items[hi] = items[hi], items[i]
quicksort(items, key, lo, i - 1)
quicksort(items, key, i + 1, hi)
return items
data = [(3, "a"), (3, "b"), (1, "c"), (3, "d"), (2, "e")]
print(quicksort(data, key=lambda r: r[0]))
# [(1, 'c'), (2, 'e'), (3, 'b'), (3, 'a'), (3, 'd')]The keys are sorted, but "b" now comes before "a". In the first partition, (1, "c") swaps with (3, "a"), and then the pivot swaps with (3, "b"). Both swaps carry an element of key 3 across other elements of key 3. A stable quicksort is possible if you partition into separate buffers instead of swapping in place. That uses O(n) extra memory and gives up quicksort's main practical advantage.
Heapsort
Heapsort builds a max-heap and then repeatedly swaps the root (the largest element) with the last element of the heap. The heap is a tree stored in an array, and its parent-child links have nothing to do with input order. The simplest failure has two elements: [(1, "a"), (1, "b")] is already a valid heap, and the first extraction swaps the root "a" to the end, giving [(1, "b"), (1, "a")]. No version of heapsort that is practical to use avoids this, because the heap property says nothing about the order of equal elements.
Summary table
| Algorithm | Stable? | Reason | Time (worst) | Extra space |
|---|---|---|---|---|
| Insertion sort | Yes | Shifts only past strictly greater keys | O(n²) | O(1) |
| Bubble sort | Yes | Adjacent swaps only on strictly greater keys | O(n²) | O(1) |
| Merge sort | Yes | Merge takes from the left run on ties | O(n log n) | O(n) |
| Counting / LSD radix sort | Yes | Backward placement keeps input order | O(n + k) per pass | O(n + k) |
| Selection sort | No | Swaps the minimum over equal keys | O(n²) | O(1) |
| Quicksort | No | Partition swaps across long distances | O(n²) | O(log n) stack |
| Heapsort | No | Heap order ignores input order | O(n log n) | O(1) |
The table shows a pattern. Among the simple comparison sorts, every O(n log n) algorithm that sorts in place with O(1) extra memory is unstable, and the stable one at that speed, merge sort, needs a buffer. This is not a proven impossibility, but in practice it is the trade-off. The hybrid algorithms covered later in the tutorial are designed around it.
Exercises
Exercise
Shell sort runs insertion sort on elements spaced h apart, for a shrinking sequence of gaps h ending at 1. Each gapped pass uses strict '>' like the stable insertion sort above. Is Shell sort stable? Explain using the movement rule.
Show answer
No. With a gap of h greater than 1, an element moves h positions in one step and passes the h - 1 elements in between, any of which may have an equal key. For example, with gap 2 on [(2,"a"), (2,"b"), (1,"c")], (1,"c") is compared with (2,"a") and swaps to the front, which gives [(1,"c"), (2,"b"), (2,"a")]. The final gap-1 pass never swaps equal neighbours, so "b" stays ahead of "a".
Exercise
A teammate's merge function uses 'if key(right[j]) < key(left[i]): take right, else take left'. Is the merge sort stable?
Show answer
Yes. On ties, key(right[j]) < key(left[i]) is false, so the else branch takes from the left run. That is the same rule as '<=' in favour of the left run, written the other way around.
Exercise
Trace selection sort on [(1,"x"), (3,"a"), (3,"b"), (2,"y")] and give the output. Is the result stable?
Show answer
Pass 1: the minimum (1,"x") is already at index 0, so nothing changes. Pass 2: the minimum of the rest is (2,"y"), which swaps with (3,"a") and gives [(1,"x"), (2,"y"), (3,"b"), (3,"a")]. Pass 3: (3,"b") and (3,"a") have equal keys, so the first one found stays and nothing swaps. The output is [(1,"x"), (2,"y"), (3,"b"), (3,"a")]. It is not stable, because "a" came before "b" in the input.