Sub topic 4
When Stability Changes the Result
This chapter assumes you can read Python, know what a key function is, and know the definition of a stable sort from the previous chapter: a stable sort keeps elements with equal keys in the order they had in the input. Here we look at when that guarantee changes what your program outputs, and when it makes no difference.
Stability only matters in some cases. If you can tell which cases those are, you avoid two mistakes. One is paying for a stable sort you don't need. The other, which is worse, is shipping code whose output depends on whatever an unstable algorithm happened to do with ties.
The Two Conditions for Stability to Matter
Stability changes the result only when both of these conditions hold:
- Ties exist. At least two elements compare as equal under the key or comparator you sort by.
- Tied elements are distinguishable. The elements that tie on the key differ in some other way you can observe, and the input order carries information you care about.
If either condition fails, every correct sort, stable or not, produces the same observable output.
| Situation | Ties? | Distinguishable? | Does stability matter? |
|---|---|---|---|
| Sorting a list of plain integers | Yes | No, two `7`s are identical | No |
| Sorting unique user IDs | No | Not applicable | No |
| Sorting records by one field out of several | Yes | Yes | Yes |
| Case-insensitive sort of `"apple"` and `"Apple"` | Yes | Yes | Yes |
| Sorting rows fetched without `ORDER BY` | Yes | Yes, but input order is arbitrary | Technically yes, but the preserved order means nothing |
The last row is a common trap, covered below.
Seeing the Difference
The quickest way to feel the difference is to run the same data through a stable sort and an unstable one. Selection sort with swaps is a simple unstable algorithm. Swapping the minimum into place can jump an element over another element with an equal key.
The data below is a list of bank transactions in chronological order, stored as (account, timestamp). We want to group them by account.
def selection_sort(items, key):
items = list(items)
for i in range(len(items)):
smallest = i
for j in range(i + 1, len(items)):
if key(items[j]) < key(items[smallest]):
smallest = j
# This long-distance swap is what breaks stability.
items[i], items[smallest] = items[smallest], items[i]
return items
transactions = [("B", 1), ("A", 2), ("B", 3), ("A", 4)]
by_account = lambda t: t[0]
print(sorted(transactions, key=by_account))
# [('A', 2), ('A', 4), ('B', 1), ('B', 3)]
print(selection_sort(transactions, key=by_account))
# [('A', 2), ('A', 4), ('B', 3), ('B', 1)]Both outputs are correctly sorted by account. Only the stable one keeps each account's transactions in time order. The unstable run put ('B', 3) ahead of ('B', 1), because the second swap moved ('B', 1) from position 1 to position 3 and carried it past ('B', 3).
Nothing in the code is buggy here. Selection sort did what it promises, which is to order by key. The program goes wrong only if later code assumes that each account's transactions are still in chronological order, for example code that computes a running balance.
Where This Shows Up in Real Programs
Sortable tables in a user interface
A user sorts a table by date, then clicks the "Status" column. They expect the rows within each status to stay in date order. With a stable sort, every click refines the previous order. With an unstable sort, rows that share a status get shuffled, and the earlier click looks as if it did nothing. The next chapter uses this effect on purpose to sort by several keys.
Leaderboards and tie-breaking by arrival
Contest submissions arrive in time order. Ranking by score with a stable sort means that among equal scores, the earlier submission ranks higher. That is often the official rule, and you get it without writing it down in the code.
submissions = [("ana", 90), ("ben", 85), ("cy", 90), ("dee", 85)]
ranked = sorted(submissions, key=lambda s: s[1], reverse=True)
print(ranked)
# [('ana', 90), ('cy', 90), ('ben', 85), ('dee', 85)]
wrong = list(reversed(sorted(submissions, key=lambda s: s[1])))
print(wrong)
# [('cy', 90), ('ana', 90), ('dee', 85), ('ben', 85)]Pagination
An API returns page 1 of results sorted by price, then page 2 in a separate request. Suppose many items share a price and the server re-sorts on every request with an unstable algorithm. Tied items can then land in a different order each time. The same item can appear on both pages, or on neither. Even a stable sort only helps if the input order is identical across requests. The reliable fix is a unique tiebreaker such as (price, id).
Reproducible output
Build tools, report generators, and test snapshots often sort before writing output. If ties are ordered arbitrarily, two runs over the same data can produce different files. That gives you noisy diffs, cache misses, and tests that fail on one platform and pass on another. Code that gets the "right" order on one platform and a different order on another is a classic symptom of depending on unstable tie order. Go's sort.Slice and C++'s std::sort, for example, guarantee nothing about ties.
Pipelines that sort more than once
Data often passes through several stages, and each stage sorts by its own field. With stable sorts, each stage keeps the meaningful order produced by earlier stages. With an unstable sort anywhere in the chain, the order of ties after that point is undefined, and every later stage inherits the loss.
When Stability Buys Nothing
Indistinguishable elements
Sorting [3, 1, 3, 2] gives [1, 2, 3, 3] whichever algorithm you use. You cannot observe which 3 came first. This is why libraries can safely use unstable sorts for primitive types. Java, for instance, uses a dual-pivot quicksort for int[] and a stable merge-based sort for object arrays.
Keys that identify the whole element
If the key is unique, such as a primary key, there are no ties. Stability is irrelevant, and an unstable sort is a fine choice for speed or memory.
Meaningless input order
Stability preserves input order. It does not create a meaningful order. Rows from a SQL query without ORDER BY, iteration over a hash map, and results merged from parallel workers all arrive in an order that may change between runs. A stable sort keeps that arbitrary order faithfully, so the output is still arbitrary among ties.
A Subtle Case: Keys That Collapse Distinct Values
Key functions often map different elements to the same key on purpose. These are sometimes called lossy keys. Common examples:
str.lowermakes"Apple"and"apple"tie.- Rounding or bucketing makes
3.14and3.15tie underround(x, 1). - Extracting a date from a timestamp makes every event on the same day tie.
words = ["banana", "Apple", "cherry", "apple", "Banana"]
print(sorted(words, key=str.lower))
# ['Apple', 'apple', 'banana', 'Banana', 'cherry']Within each case-insensitive group, the output follows the input order. "Apple" precedes "apple" and "banana" precedes "Banana" because that is how they arrived. A user who sees banana before Banana but Apple before apple may report it as a bug. If you want a consistent rule, say it in the key: key=lambda w: (w.lower(), w).
Checklist
Before choosing a sort, ask:
- Can two elements compare equal under my key?
- If so, can anyone downstream tell them apart?
- Does the input order carry meaning, and is it guaranteed to be the same every time?
- Would an explicit tiebreaker state my intent more clearly than relying on stability?
Exercise
You sort a list of log entries by severity using an unstable sort. The entries were read from a file in timestamp order. A colleague says this is fine "because severity is the only thing we display." Under what change would this become a bug, and what are two ways to fix it?
Show answer
It becomes a bug as soon as anything observes order within a severity level: displaying timestamps, showing the first N entries of a level, diffing outputs between runs, or a later stage assuming chronological order. One fix is to use a stable sort, which keeps file order (timestamp order) within each severity. The other is to sort by the composite key (severity, timestamp), which works with any correct sort and doesn't depend on the input order.
Exercise
Given scores = [("x", 2), ("y", 1), ("z", 2)], what do sorted(scores, key=lambda s: s[1], reverse=True) and list(reversed(sorted(scores, key=lambda s: s[1]))) return, and why do they differ?
Show answer
The first returns [('x', 2), ('z', 2), ('y', 1)], because reverse=True keeps tied elements in input order. The second sorts ascending to [('y', 1), ('x', 2), ('z', 2)], then reverses everything to [('z', 2), ('x', 2), ('y', 1)]. Reversing also flipped the tie between x and z.
Exercise
An endpoint returns products sorted by price using a stable sort, 20 per page. The products come from a database query with no ORDER BY. Users report seeing the same product on page 1 and page 2. Why doesn't stability prevent this, and what is the fix?
Show answer
Stability keeps whatever order the input had, but without ORDER BY the database may return rows in a different order on each request. So the order of products with the same price can differ between the page 1 and page 2 requests. The fix is a deterministic total order: sort by (price, id), or add ORDER BY price, id to the query.