Sub topic 3
What Makes a Sort Stable
This chapter defines stability precisely and shows how to check whether a given sorted output is stable. It assumes you can write basic code in a mainstream language, know how lists and records work, can read Big-O notation, and have passed a key function or lambda to a sort before. The previous chapter covered keys and comparators. Here we use them to say exactly which elements count as "equal" and what a stable sort must do with them.
The definition
A sort is stable if elements with equal keys appear in the output in the same relative order they had in the input.
Stated more carefully: suppose the input is a sequence a[0], a[1], ..., a[n-1] and the sort uses some key or comparator. A sort is stable if, for every pair of positions i < j where a[i] and a[j] compare as equal, a[i] comes before a[j] in the output.
The definition has three parts, and each one matters:
- "Compare as equal" means neither element is less than the other under the comparator. The elements themselves can differ in every field the key ignores.
- "Relative order" means only the order within a group of equal elements. Elements with different keys are placed by the key, so stability says nothing about them.
- "For every pair" means this must hold for every input, not just the one you tried.
An unstable sort makes no promise about equal elements. It must still produce a correctly sorted output, but within each group of equal keys any arrangement is allowed.
A worked example
Take four records sorted by score:
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, so they form an equal-key group. Alice was at input position 0 and Carol at position 2, so a stable sort must put Alice first.
| Input position | Record | Key | Output position |
|---|---|---|---|
| 0 | alice | 3 | 2 |
| 1 | bob | 1 | 0 |
| 2 | carol | 3 | 3 |
| 3 | dave | 2 | 1 |
Bob and Dave have unique keys, so their placement is fully decided by the key. Only the Alice–Carol pair is subject to the stability rule.
An unstable sort could also return [('bob', 1), ('dave', 2), ('carol', 3), ('alice', 3)]. That output is correctly sorted by score. It is just not the stable one.
How many correct outputs exist
Stability turns a sorting problem with several correct answers into one with exactly one correct answer.
If the input has equal-key groups of sizes g1, g2, ..., gk, then the number of correctly sorted outputs is g1! × g2! × ... × gk!. Each group can be arranged internally in any order. In the example, the score-3 group has size 2 and the others have size 1, so there are 2! × 1! × 1! = 2 valid sorted outputs. A stable sort must return one specific output: the one where each group keeps its input order.
This uniqueness has practical value. Two different stable sort implementations, given the same input and key, must produce the same output. Two unstable implementations, or the same unstable implementation in a different library version, may not. This is why test snapshots and paginated results can change after an upgrade when the code relies on an unstable sort.
Checking a given output
To decide whether a specific output is stable, you need to know where each output element came from. Comparing records by value is not enough, because two records might be identical in every field. The reliable approach is to track original positions.
The function below takes the input, the output expressed as a list of original indices, and the key. It reports whether the output is sorted and whether it preserves input order among equal keys.
def check_output(items, order, key):
"""order[k] is the input index of the element at output position k."""
out = [items[i] for i in order]
is_sorted = all(key(a) <= key(b) for a, b in zip(out, out[1:]))
is_stable = all(
i < j
for i, j in zip(order, order[1:])
if key(items[i]) == key(items[j])
)
return is_sorted, is_stable
records = [("alice", 3), ("bob", 1), ("carol", 3), ("dave", 2)]
score = lambda r: r[1]
print(check_output(records, [1, 3, 0, 2], score)) # (True, True)
print(check_output(records, [1, 3, 2, 0], score)) # (True, False)
print(check_output(records, [0, 1, 2, 3], score)) # (False, True)The function checks only adjacent pairs, and that is enough. In a correctly sorted output, all elements with the same key are contiguous. If every adjacent pair inside a group is in increasing index order, the whole group is in increasing order by transitivity. Note that the third call shows the stability check by itself means little: an unsorted output can trivially "preserve order". Stability is only meaningful once the output is sorted.
When stability is invisible
Stability only matters when equal elements can be told apart.
If you sort a list of plain integers, two equal 7s are interchangeable. No program can observe whether they were swapped, so stable and unstable sorts give indistinguishable results. This is why some libraries happily use unstable sorts for primitive types. Java, for example, uses a quicksort variant for int[] and a stable merge-based sort for object arrays.
Stability becomes visible when:
- The key is only part of the element, as with records sorted by one field.
- The key is a transformation of the element, such as case-insensitive string sorting, where
"Apple"and"apple"have the same key but different values. - The elements are objects with identity, so two equal-valued objects are still different objects that other code may hold references to.
Stability is also always relative to the key. The same list can have many equal-key groups under one key and none under another. If every element has a distinct key, every correct sort is stable by default, because there are no ties to preserve.
Reversal and descending order
Descending sorts are a common source of accidental instability, because there are two ways to get descending output and they give different results.
records = [("alice", 3), ("bob", 1), ("carol", 3), ("dave", 2)]
score = lambda r: r[1]
desc = sorted(records, key=score, reverse=True)
print(desc)
# [('alice', 3), ('carol', 3), ('dave', 2), ('bob', 1)]
flipped = list(reversed(sorted(records, key=score)))
print(flipped)
# [('carol', 3), ('alice', 3), ('dave', 2), ('bob', 1)]Python's reverse=True is defined to keep stability. It reverses the comparison, not the result, so Alice still precedes Carol. Sorting ascending and then reversing the list flips every equal-key group too, which puts Carol first. The second output is sorted in descending order, but it is not the stable descending sort of the input.
The same reasoning applies in other languages. In Java, Comparator.reversed() reverses the comparison and keeps List.sort stable. Calling Collections.reverse after an ascending sort does not.
Common misconceptions
| Misconception | What is actually true |
|---|---|
| Stable means the sort leaves already-sorted input unchanged | Every correct sort leaves strictly sorted input with distinct keys unchanged. Stability is about ties. |
| Stable means in-place | These are independent properties. Merge sort is stable but usually needs extra memory. Heapsort is in-place but unstable. |
| Equal means identical | Equal means equivalent under the comparator. The elements may differ in every other field. |
| If my test output looked stable, the sort is stable | Only a documented guarantee or a proof establishes stability. Tests can only find violations. |
| The default sort in every language is stable | Python, Java (for objects), JavaScript (since ES2019) and Rust's `sort` are stable. C++ `std::sort`, Go's `sort.Slice` and Rust's `sort_unstable` are not. |
Summary
A stable sort keeps elements that compare as equal in their input order. That rule picks one specific output from all the correctly sorted ones. You check stability by tracking original positions, and within a sorted output it is enough to compare adjacent pairs. Stability depends on the key, matters only when equal elements can be told apart, and is lost if you reverse a list after sorting it.
Exercise
Input: [("x", 2), ("y", 1), ("z", 2), ("w", 1), ("v", 2)], sorted by the second field. How many correctly sorted outputs exist, and what is the single stable output?
Show answer
The key-1 group has size 2 (y, w) and the key-2 group has size 3 (x, z, v), so there are 2! × 3! = 12 correctly sorted outputs. The stable one keeps input order within each group: [("y", 1), ("w", 1), ("x", 2), ("z", 2), ("v", 2)].
Exercise
A sort of records [(0, "a"), (1, "b"), (2, "a"), (3, "b")] by the letter returns them in input-index order [2, 0, 1, 3]. Is the output sorted? Is it stable? Use the adjacent-pair rule.
Show answer
It is sorted: a, a, b, b. It is not stable: the adjacent pair with indices 2 and 0 has equal keys ("a") but 2 > 0, so index 2 was placed ahead of index 0.
Exercise
You sort a list of integers with an unstable sort and a stable sort, and both outputs are identical on every input you try. Does this show the unstable sort is actually stable? Explain.
Show answer
No. Equal integers cannot be told apart, so stability is unobservable here and the outputs must look identical. To expose instability you need elements whose keys tie but which carry distinguishing data, such as their original index.
Exercise
Why does sorted(records, key=score, reverse=True) give a different result from list(reversed(sorted(records, key=score))) when records contains ties?
Show answer
reverse=True reverses the comparison, so equal elements keep their input order. Reversing the finished list also reverses the order inside each equal-key group, so ties come out in reverse input order and the result is not the stable descending sort.