Sub topic 4
When Stability Changes the Result
This chapter assumes you can read basic Python and that you already know the definition from the previous chapter: a stable sort keeps elements with equal keys in their original input order. The question here is practical. When does that guarantee change what your program outputs, and when does it make no difference?
Equal keys only matter when the elements differ
Stability affects only elements whose keys compare equal. If two such elements are identical in every respect, as when you sort a plain list of integers, no one can tell which 3 came first, so a stable and an unstable sort produce the same output.
The difference shows up when the sort key is only part of each element. Sort order records by status and two "shipped" orders compare as equal. They still have different IDs, timestamps and customers, so their relative position becomes visible in the output.
A worked example
Suppose a list of orders is already in time order, and you want to group the orders by status while keeping each group in time order. The code below sorts the list two ways. The first uses Python's sorted, which is stable. The second uses a selection sort, which swaps elements over long distances and is therefore unstable.
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
items[i], items[smallest] = items[smallest], items[i]
return items
# Already in time order.
orders = [
("09:00", "shipped", "o1"),
("09:05", "shipped", "o2"),
("09:10", "pending", "o3"),
]
by_status = lambda order: order[1]
stable = sorted(orders, key=by_status)
unstable = selection_sort(orders, key=by_status)
print([o[2] for o in stable]) # ['o3', 'o1', 'o2']
print([o[2] for o in unstable]) # ['o3', 'o2', 'o1']Both results are correctly sorted by status. In the unstable result, however, o2 (09:05) appears before o1 (09:00). The first swap moved o1 from the front of the list to the back, past its equal neighbour o2. Nothing about status was violated, but the time order the input carried has been lost.
Situations where you will notice
| Situation | What goes wrong without stability |
|---|---|
| Clicking table columns in a UI to re-sort | The previous column's order inside each group is scrambled |
| Grouping log events by severity | Events within a severity level are no longer in chronological order |
| Ranking with ties (scores, prices) | Tied items change places between runs or library versions |
| Paginating sorted results | A tied item can appear on two pages or on none |
| Snapshot or golden-file tests | Output changes when the sort implementation changes |
The last two rows come from a related property, determinism. An unstable sort may place tied elements differently depending on input size, pivot choice or library version. A stable sort's output is fully determined by the input order.
Deciding whether you need it
The most common case where input order carries meaning is that an earlier sort put the data in that order. The next chapter builds on this to sort by several keys.
Exercise
A list of employees is in hire-date order. You sort it by department using an unstable sort, and two employees in the same department, hired in 2019 and 2021, come out with the 2021 hire first. Is the sort output wrong? What would you change to get departments with employees in hire-date order inside each one?
Show answer
The output is correctly sorted by department, so the sort did nothing wrong; an unstable sort only promises key order. To keep hire-date order inside each department, either use a stable sort (the input is already in hire-date order) or sort by the composite key (department, hire date).
Exercise
You sort a list of plain integers [4, 1, 4, 2] with an unstable sort. Can the result differ from what a stable sort produces?
Show answer
No. Both produce [1, 2, 4, 4]. The two 4s are indistinguishable, so their relative order cannot be observed.