Sub topic 3
What Makes a Sort Stable
This chapter assumes you can read basic Python, know what a list of tuples or records is, and have seen a key function passed to a sort. The previous chapter showed that a comparator can call two different elements "equal" when their keys match. This chapter covers what a sort does with those equal elements.
The definition
A sort is stable if any two elements with equal keys come out in the same relative order they had in the input.
Put formally: suppose elements x and y have equal keys and x appears before y in the input. A stable sort guarantees that x also appears before y in the output. An unstable sort makes no such promise, so it may put y first.
Stability only matters when equal-keyed elements can be told apart. If you sort plain integers, two 3s look the same, so you cannot see their order. If you sort records by one field, two records with the same score can still differ in their other fields. In that case the order of the tied records is visible, and it may matter to your program.
A worked example
records = [("alice", 3), ("bob", 1), ("carol", 3), ("dave", 2)]
by_score = sorted(records, key=lambda r: r[1])
print(by_score)
# [('bob', 1), ('dave', 2), ('alice', 3), ('carol', 3)]Python's sorted is guaranteed stable. alice and carol both have score 3. alice came first in the input, so she comes first in the output. An unstable sort could legally return [('bob', 1), ('dave', 2), ('carol', 3), ('alice', 3)]. Both outputs are correctly sorted by score, but only the first one is stable.
Checking an output by hand
To decide whether a given output is consistent with a stable sort:
- Group the elements by key.
- For each group, list the members in the order they appear in the input.
- Check that the output lists each group's members in that same order.
If any group comes out reordered, the sort that produced it is not stable.
| Key | Input order | Output order | Preserved? |
|---|---|---|---|
| 1 | bob | bob | yes |
| 2 | dave | dave | yes |
| 3 | alice, carol | alice, carol | yes |
Common mistakes
Other errors to watch for:
- Treating a stable result as "more sorted." Both stable and unstable outputs are fully sorted by the key. Stability only affects how ties are ordered.
- Assuming the whole element is the key. Stability is defined relative to the key you sort by. Two records that differ only in a field you did not sort on count as equal.
- Assuming the default sort is stable. Some languages guarantee stability in the default sort and others do not. A later chapter surveys which ones do.
Exercise
The input is [("x", 2), ("y", 1), ("z", 2), ("w", 1)], sorted by the second field. Output A is [("y", 1), ("w", 1), ("x", 2), ("z", 2)]. Output B is [("w", 1), ("y", 1), ("x", 2), ("z", 2)]. Which output could come from a stable sort, and why is the other one ruled out?
Show answer
Only output A. In the input, "y" comes before "w" (both key 1) and "x" comes before "z" (both key 2). Output A keeps both orders. Output B puts "w" before "y", which reverses two equal-keyed elements, so a stable sort cannot produce it. Output B is still correctly sorted by key.
Exercise
You sort a list of integers with an unstable algorithm and the output is [1, 2, 2, 3]. Can you tell whether the two 2s were swapped?
Show answer
No. The two 2s are indistinguishable, so their relative order cannot be observed. Stability only becomes visible when elements with equal keys carry other data that tells them apart.