Sub topic 4
What Stability Means and Why It Matters
This chapter assumes you can read Python functions that take a key argument, know Big-O notation, and have seen at least one comparison sort. It also assumes you have read the previous chapter, which covered the histogram version of counting sort.
The histogram version counts how many times each value appears and then writes the values back in order. That works for bare integers. It breaks as soon as each key has data attached to it, such as a customer record sorted by age or a log line sorted by severity. Once the key comes with data, two records can share a key and still be different records. Their order in the output then matters. That order is what stability describes.
The Definition
A sort is stable if records with equal keys come out in the same relative order they had in the input.
Stated precisely: if records x and y have key(x) == key(y) and x appears before y in the input, then a stable sort places x before y in the output. A sort that does not guarantee this is unstable. An unstable sort may still keep the original order on some inputs. It just doesn't promise to.
Here is a small input sorted by the number in each pair:
| Input position | Record | Key |
|---|---|---|
| 0 | ("ana", 2) | 2 |
| 1 | ("bo", 1) | 1 |
| 2 | ("cy", 2) | 2 |
| 3 | ("di", 0) | 0 |
A stable sort must produce di, bo, ana, cy. The output di, bo, cy, ana is also sorted by key, but it swaps the two records with key 2, so a stable sort can never produce it.
Why the Histogram Version Can't Be Stable
The histogram version of counting sort stores only counts[v], the number of times value v appears. When it rebuilds the array it writes v out counts[v] times. For bare integers this is fine, because two copies of the integer 2 are indistinguishable.
With records, the count array has thrown away the information you need. It knows that two records have key 2, but not which records they were or which came first. Stability for bare integers is a meaningless question. For records it is unanswerable unless the algorithm keeps the records themselves.
One direct fix is to keep a list per key, append records in input order, and then concatenate the lists:
def bucket_sort_by_key(items, key, k):
"""Stable sort of items whose key(item) is an integer in 0..k."""
buckets = [[] for _ in range(k + 1)]
for item in items: # input order is preserved inside each bucket
buckets[key(item)].append(item)
return [item for bucket in buckets for item in bucket]
people = [("ana", 2), ("bo", 1), ("cy", 2), ("di", 0)]
print(bucket_sort_by_key(people, lambda p: p[1], 2))
# [('di', 0), ('bo', 1), ('ana', 2), ('cy', 2)]This is stable because each bucket is filled in input order and nothing reorders a bucket afterward. It costs a separate list per key, many small allocations, and poor memory locality. The next two chapters get the same guarantee using one flat output array and a count array turned into positions. Keep this version in mind as the reference behavior.
Seeing Instability in Action
Many sorts that swap elements over long distances are unstable. Selection sort is the textbook example. It finds the minimum of the unsorted part and swaps it to the front. That swap can jump a record over another record with the same key.
def selection_sort_by_key(items, key):
a = list(items)
n = len(a)
for i in range(n):
m = i
for j in range(i + 1, n):
if key(a[j]) < key(a[m]):
m = j
a[i], a[m] = a[m], a[i]
return a
data = [("a", 2), ("b", 2), ("c", 1)]
print(selection_sort_by_key(data, lambda p: p[1]))
# [('c', 1), ('b', 2), ('a', 2)]On the first pass, the minimum ("c", 1) swaps with ("a", 2), which sends a to the end, past b. The output is correctly sorted by key, yet a and b have changed places. Heapsort and the usual in-place quicksort partitions are unstable for the same reason. Merge sort, insertion sort, and Python's built-in sorted (Timsort) are stable.
Testing a sort for stability
A single example can show that a sort is unstable. It cannot show that a sort is stable. Still, a quick randomized check catches most bugs. Tag every record with its input index, sort, and confirm that the indices increase within each run of equal keys:
import random
def preserves_order(sort_fn, items, key):
"""Return True if sort_fn kept equal-key records in input order on this input."""
tagged = list(enumerate(items))
result = sort_fn(tagged, lambda t: key(t[1]))
for (i1, x1), (i2, x2) in zip(result, result[1:]):
if key(x1) > key(x2):
raise ValueError("output is not sorted")
if key(x1) == key(x2) and i1 > i2:
return False
return True
def bucket_sort_by_key(items, key, k):
buckets = [[] for _ in range(k + 1)]
for item in items:
buckets[key(item)].append(item)
return [item for bucket in buckets for item in bucket]
def selection_sort_by_key(items, key):
a = list(items)
n = len(a)
for i in range(n):
m = i
for j in range(i + 1, n):
if key(a[j]) < key(a[m]):
m = j
a[i], a[m] = a[m], a[i]
return a
random.seed(1)
trials = [[random.randint(0, 3) for _ in range(20)] for _ in range(200)]
ident = lambda x: x
print(all(preserves_order(lambda xs, kf: bucket_sort_by_key(xs, kf, 3), t, ident) for t in trials))
print(all(preserves_order(selection_sort_by_key, t, ident) for t in trials))
# True
# FalseUse a small key range such as 0..3 so that ties are frequent. With keys drawn from a large range, ties are rare and an unstable sort can pass by luck.
Why Stability Matters
Sorting by several keys in passes
Stability lets you sort by several keys using several simple passes. To order employees by department, and by name within each department, you sort by the secondary key first and then by the primary key with a stable sort:
staff = [
("Rao", "ops"), ("Kim", "dev"), ("Abe", "ops"),
("Lee", "dev"), ("Cho", "ops"),
]
by_name = sorted(staff, key=lambda s: s[0]) # secondary key first
by_dept = sorted(by_name, key=lambda s: s[1]) # primary key last, stable
print(by_dept)
# [('Kim', 'dev'), ('Lee', 'dev'), ('Abe', 'ops'), ('Cho', 'ops'), ('Rao', 'ops')]The second pass groups records by department. Within one department every key ties, so a stable sort leaves those records in the order the first pass created, which is alphabetical. If the second sort were unstable, the names inside each department could come out scrambled.
This is the central idea behind LSD radix sort, which later chapters build. LSD radix sort treats each digit of an integer as a separate key and sorts from the least significant digit to the most significant, one stable pass per digit. Each pass relies on stability to keep the order set by the earlier passes. With an unstable counting sort inside, radix sort gives wrong answers.
Predictable output
Stability also matters on its own. If a table in a user interface is re-sorted by a column with many ties, a stable sort keeps the rows from shuffling between renders. If you sort events by timestamp and two events share a timestamp, a stable sort keeps them in arrival order. Tests that compare sorted output also stay deterministic.
Making Any Sort Stable
You can force stability on any sort by extending the key with the input index, so that no two keys are ever equal:
def make_stable(sort_fn):
def stable_sort(items, key):
tagged = list(enumerate(items))
result = sort_fn(tagged, lambda t: (key(t[1]), t[0]))
return [item for _, item in result]
return stable_sort
def selection_sort_by_key(items, key):
a = list(items)
n = len(a)
for i in range(n):
m = i
for j in range(i + 1, n):
if key(a[j]) < key(a[m]):
m = j
a[i], a[m] = a[m], a[i]
return a
stable_selection = make_stable(selection_sort_by_key)
print(stable_selection([("a", 2), ("b", 2), ("c", 1)], lambda p: p[1]))
# [('c', 1), ('a', 2), ('b', 2)]This costs O(n) extra memory for the indices and makes every comparison a tuple comparison. For counting sort the trick is useless, because the composite key (key, index) has a range of about k * n values, which defeats the purpose of counting. Counting sort has to be stable by construction, and the prefix-sum version in the next chapters is.
Common Mistakes
| Mistake | Symptom | Fix |
|---|---|---|
| Assuming "sorted output" means "stable" | Multi-key or radix results are wrong only on inputs with ties | Test with a small key range so ties are common |
| Sorting the primary key first in a multi-pass sort | Final order is grouped by the secondary key | Sort from the least important key to the most important |
| Using an unstable inner sort in radix sort | Numbers come out in the wrong order after the second digit | Use a stable counting sort for each digit |
| Mismatched scan and fill directions | Equal keys come out reversed | Scan forward and fill forward, or scan backward and fill backward |
| Checking stability on bare integers | Every test passes because equal integers can't be told apart | Tag items with their input index before sorting |
Exercise
Sort the records [("p", 1), ("q", 0), ("r", 1), ("s", 0), ("t", 1)] by key with a stable sort. Then give one key-sorted output that a stable sort cannot produce.
Show answer
Stable output: [("q", 0), ("s", 0), ("p", 1), ("r", 1), ("t", 1)]. The key-0 records keep the order q, s and the key-1 records keep p, r, t. Any output that breaks either order is sorted but unstable, for example [("s", 0), ("q", 0), ("p", 1), ("r", 1), ("t", 1)].
Exercise
You need log entries ordered by severity, and by time within each severity. Using only a stable sort, which key do you sort by first, and why?
Show answer
Sort by time first, then by severity. The second (stable) pass groups entries by severity. Within one severity all keys tie, so the pass keeps the time order the first pass produced. Sorting by severity first would let the time sort scatter the severity groups.
Exercise
In bucketsortby_key, replace "for item in items" with "for item in reversed(items)" and leave everything else unchanged. Is the result still sorted? Is it stable?
Show answer
It is still sorted by key, because the buckets are concatenated in key order. It is not stable: every bucket is now filled in reverse input order, so each group of equal keys comes out reversed. For the people example the output becomes [('di', 0), ('bo', 1), ('cy', 2), ('ana', 2)].