Sub topic 4
What Stability Means and Why It Matters
This chapter assumes you know basic Python, including lists, tuples, and lambda. It also assumes you have used at least one comparison sort, such as merge sort or quicksort. The previous chapter's counting sort output bare integers. Real programs usually sort records, such as rows, objects, or tuples, by one field. Once you sort records, a new question comes up: what happens to records whose keys are equal?
The definition
A sort is stable if records with equal keys appear in the output in the same relative order they had in the input. If record A came before record B and both have key 2, a stable sort guarantees A still comes before B. An unstable sort may swap them.
Stability only matters when equal keys can belong to records that differ in some other way. Sorting the bare list [3, 1, 1] gives [1, 1, 3] either way, because the two 1s cannot be told apart. That is why the histogram version of counting sort never had to think about stability. It throws the original elements away and writes fresh copies of each value, so it cannot carry attached data at all.
Stable and unstable sorts side by side
Python's built-in sorted is stable. A textbook selection sort is not, because its long-distance swaps can jump one record past another record with the same key.
def selection_sort_by_key(items, key):
a = list(items)
for i in range(len(a)):
m = i
for j in range(i + 1, len(a)):
if key(a[j]) < key(a[m]):
m = j
a[i], a[m] = a[m], a[i] # this swap can reorder equal keys
return a
records = [("a", 2), ("b", 2), ("c", 1)]
print(sorted(records, key=lambda r: r[1]))
# [('c', 1), ('a', 2), ('b', 2)] stable: a stays before b
print(selection_sort_by_key(records, lambda r: r[1]))
# [('c', 1), ('b', 2), ('a', 2)] unstable: a and b swappedOn the first pass, selection sort swaps ("c", 1) into position 0. That moves ("a", 2) to the end, behind ("b", 2), and nothing later puts it back.
Why it matters: sorting by several keys
Stability lets you build a multi-key sort out of single-key sorts. Sort by the least important key first, then do a stable sort by the more important key. Records that tie on the important key keep the order from the earlier pass.
employees = [("cy", "eng"), ("ana", "ops"), ("bo", "eng"), ("di", "ops")]
step1 = sorted(employees, key=lambda e: e[0]) # secondary key: name
step2 = sorted(step1, key=lambda e: e[1]) # primary key: department
print(step2)
# [('bo', 'eng'), ('cy', 'eng'), ('ana', 'ops'), ('di', 'ops')]The result is grouped by department, and names are alphabetical inside each group. If the second sort were unstable, the alphabetical order from step 1 could be scrambled.
Common errors
- Assuming every sort is stable. Quicksort and heapsort, in their usual forms, are not stable. Check your library's documentation. For example, C++
std::sortis unstable andstd::stable_sortis stable. - Running the passes in the wrong order. The last pass sets the primary order, so sort by the most important key last.
- Testing only with bare values. A test with distinct-looking but equal-keyed records, like the ones above, is the only way to catch instability.
The next chapter shows how prefix sums let counting sort place records directly into their final slots while keeping this guarantee.
Exercise
You sort the records [("x", 3), ("y", 1), ("z", 3), ("w", 1)] by their number using a stable sort. What is the output, and which output orders would an unstable sort also be allowed to produce?
Show answer
A stable sort must produce [("y", 1), ("w", 1), ("x", 3), ("z", 3)]. An unstable sort may also swap y and w, swap x and z, or both, so it could produce any of four outputs. All four are sorted by key, but only the first keeps the input order among equal keys.
Exercise
You want a list of students sorted by grade, with ties broken by surname. You have only a stable single-key sort. In what order do you run the two sorts, and why?
Show answer
Sort by surname first, then by grade. The last stable pass sets the primary order (grade). Within each grade, stability keeps the surname order produced by the first pass.