Stable Sorting with Equal Keys
A stable sort preserves the original relative order of records that compare equal, so only ties are affected. Stability matters when an earlier ordering carries meaning, such as a secondary key or an arrival sequence, and it is a property of the algorithm rather than the comparator.
The short answer
A sort is stable when records that compare equal keep their original relative order. Records with different keys are unaffected: stability constrains only ties. It matters when the current order carries information, such as a secondary sort key, an arrival sequence, or a priority assigned earlier. Python's sorted, Java's object sorts, and JavaScript's Array.prototype.sort are specified as stable; C++ std::sort and Go's sort.Slice are not, and each has a stable counterpart.
A minimal example
people = [("carol", 30), ("alice", 30), ("bob", 25)]
people.sort(key=lambda p: p[0]) # name
people.sort(key=lambda p: p[1]) # age, stable
print(people)
# [('bob', 25), ('alice', 30), ('carol', 30)]
The second sort orders by age. Alice and Carol tie at 30, and Alice comes first because the name sort put her first and the stable age sort left the tie alone. An unstable sort could return either order, so the result would depend on the algorithm rather than the data.
Why this happens
Stability is a property of the algorithm, not the comparator. Sorts that only exchange adjacent out-of-order elements, such as insertion sort and a merge sort that takes from the left run on ties, never move equal keys past each other. Partition-based sorts do: quicksort swaps elements from opposite ends across a pivot, and heapsort moves elements over long distances during sift operations. Either can invert a tie.
For merge sort the tie rule is explicit: when the two front elements are equal, take the one from the left run. Using < instead of <= to choose the right run on ties silently destroys stability.
Where the guarantee stands
| API | Stable | Algorithm or note |
|---|---|---|
Python list.sort, sorted |
Yes | Timsort |
Java Arrays.sort(Object[]), List.sort |
Yes | Timsort for objects |
Java Arrays.sort on primitives |
Not specified | Dual-pivot quicksort; primitives have no identity |
JavaScript Array.prototype.sort |
Yes | Required since ES2019 |
C++ std::sort |
No | std::stable_sort is |
Go sort.Slice |
No | sort.SliceStable is |
What changes the answer
If ties are meaningful, prefer a composite key over relying on stability: sorting by (age, name) produces a total order in one pass and does not depend on the sort's internals. Use stability when the secondary order is expensive to recompute or is not expressible as a key, such as an order established by earlier processing.
Reversal deserves care. In Python, reverse=True reverses the comparison but preserves stability, so equal keys keep their original order rather than being reversed. Some APIs implement reverse by negating the comparator, which can invert ties; check the documentation rather than assuming symmetry.
Stability also matters across library boundaries. A function that promises "sorted by key" without specifying stability is making a weaker promise than one that says "stable". If callers depend on tie order, the contract must say so.
Practical checks
Read the documentation for the exact API you call; do not infer stability from a test with a few elements, because unstable sorts often look stable on small inputs. When composing sorts, sort by the least significant key first and rely on stable passes for the rest, or build a tuple key and sort once. If ties carry no meaning, do not pay for stability.
A stable sort pairs naturally with boundary search: after sorting records by a key, a left-boundary search returns the first record of a run of equal keys, which under stability is the earliest one in the original order. The mechanics of that search are covered in finding the left boundary with binary search.
Sources
Revision history
- Published
- Updated
- — Initial publication.