Skip to content
Craft

What is a stable sort and why does it matter?

What is a stable sort? It is a sort that keeps equal-keyed records in their original relative order. Here is why that one guarantee powers multi-key sorting and radix sort, which algorithms have it, and how to get it when yours does not.

What is a stable sort? It is a sorting algorithm that keeps records with equal keys in the same relative order they had in the input. If two invoices both dated March 3 enter the sort with invoice A before invoice B, a stable sort guarantees A still precedes B in the output.

Most people meet the word once, in a lecture table with a column of yes and no, and then forget it. That is a mistake, because stability is the property that lets you sort by several fields without writing a complicated comparator, and it is the property that makes radix sort correct at all. This essay covers what the guarantee means, where it comes from inside the algorithm, what it costs, and how to get it when your tools do not offer it.

Why does stability matter if equal keys are equal anyway?

Equal keys are only equal in the field you sorted on. The records carrying them have other fields, and the order of those other fields is information that an unstable sort is free to destroy.

Think about a spreadsheet of support tickets. You sort by creation time, so the oldest ticket sits on top. Then you click the priority column. You expect the high-priority tickets to appear together, and within that group you expect them to still be oldest first, because that is the order you just established. A stable sort delivers exactly that. An unstable sort hands you the high-priority group in an arbitrary shuffle, and the creation-time order you built a moment ago is gone.

Here is the framing I find most useful, and the one I would offer a junior engineer. A stable sort treats the input order as a hidden extra column of tiebreakers. You never wrote that column, but it is there, and the algorithm honours it. An unstable sort ignores the column. Once you see stability this way, the practical consequences follow without memorising anything: whenever the input order means something (time, arrival, a previous sort), stability preserves it for free.

When the input order means nothing, stability is irrelevant. If you sort a list of plain integers, two 7s are indistinguishable, so swapping them changes nothing you can observe. Stability only becomes observable when records are distinguishable by something other than the sort key.

Which sorting algorithms are stable?

Merge sort, insertion sort, bubble sort, Timsort and counting sort (written the right way) are stable. Selection sort, heap sort and the usual in-place quicksort are not. The split follows one question: does the algorithm ever move an element across other elements that have an equal key?

AlgorithmStable?Worst-case timeExtra spaceWhere stability is won or lost
Insertion sortYesO(n^2)O(1)Shifts only while the left neighbour is strictly greater
Bubble sortYesO(n^2)O(1)Swaps only adjacent, strictly out-of-order pairs
Merge sortYesO(n log n)O(n)Merge takes from the left run on ties
TimsortYesO(n log n)O(n)Merges of runs follow the same tie rule
Counting sortYesO(n + k)O(n + k)Output is filled by scanning the input backwards
Selection sortNoO(n^2)O(1)Long-distance swap of the minimum
Heap sortNoO(n log n)O(1)Root swapped with the last leaf
Quicksort (in place)NoO(n^2)O(log n)Partition swaps across equal elements

Let me make the failure concrete, because the table can look arbitrary until you watch an unstable sort misbehave. Take three records with keys 2, 2, 1, and label the two 2s as 2a and 2b so we can tell them apart. Selection sort scans for the smallest element, finds the 1 at index 2, and swaps it with whatever sits at index 0. The array becomes [1, 2b, 2a]. Nothing about the sort looked wrong, yet 2a and 2b traded places. One long-distance swap was enough.

Quicksort fails the same way. Using the common Lomuto partition with the last element (the 1) as pivot, no element is smaller than the pivot, so the pivot is swapped into position 0, and again the result is [1, 2b, 2a]. Heap sort fails because it repeatedly swaps the root with the last leaf, which has no relationship to the order of equal keys. These are not bugs. They are the price of moving elements across large distances in O(1) extra space.

Where does stability actually come from inside the algorithm?

In merge sort it comes from a single character in a comparison. The merge step looks at the front of the left run and the front of the right run, and when the two keys are equal it must take from the left. Take from the right instead and you have an unstable merge sort that is otherwise identical.

def merge(left, right, key):
    out, i, j = [], 0, 0
    while i < len(left) and j < len(right):
        if key(left[i]) <= key(right[j]):   # <= keeps ties in input order
            out.append(left[i]); i += 1
        else:
            out.append(right[j]); j += 1
    out.extend(left[i:])
    out.extend(right[j:])
    return out

The left run always contains elements that came earlier in the input than anything in the right run. So preferring the left on a tie is precisely the statement "earlier input position wins". Change <= to < and the proof of stability collapses, even though the output is still correctly sorted. That is the sneaky part: an unstable sort is still a correct sort. Stability is an extra promise, and no test that only checks sortedness will notice you broke it.

Insertion sort is stable for a parallel reason. It slides an element left only while the neighbour is strictly greater, so it stops the moment it meets an equal key and never hops over one. The same < versus <= decision decides everything. If you ever write your own insertion sort and use >= in the shifting loop, you have quietly made it unstable.

How does a stable sort make multi-key sorting work?

You sort by the least significant key first and the most significant key last. Each stable pass preserves the order produced by the passes before it, so the final pass groups by the main key while the earlier passes survive as tiebreakers inside each group.

Here is a small worked example. Five employees, and the goal is to order by department, then by name within a department:

employees = [('Kim','ops'), ('Ana','eng'), ('Raj','ops'),
             ('Bea','eng'), ('Cho','ops')]
employees.sort(key=lambda e: e[0])   # pass 1: by name
employees.sort(key=lambda e: e[1])   # pass 2: by department
print(employees)

After pass 1 the list is Ana, Bea, Cho, Kim, Raj, in name order. Pass 2 sorts by department. The two eng records, Ana and Bea, entered the pass in that order, so they leave in that order. The three ops records, Cho, Kim and Raj, do likewise. The result is Ana and Bea (eng), then Cho, Kim and Raj (ops). Run the same two passes with an unstable sort and the ops group could come out as Raj, Cho, Kim, because the department pass had no reason to preserve what the name pass built.

A picture I like here is sediment. Every stable pass lays down a layer, and the last pass is the layer on top, the one you read first. The earlier layers are still there underneath, and they decide every tie the upper layers leave open. An unstable pass is like stirring the jar: you keep the top colour but lose the strata.

The alternative is a single pass with a composite key, such as key=lambda e: (e[1], e[0]). That is often cleaner, and it is what I would write in new code. The two-pass approach earns its place when the keys come from different places in a program, for example when a table lets users click column headers one after another. Each click is a sort by one key, and the stability of the underlying sort is what turns a series of independent clicks into a coherent multi-column ordering.

Why does radix sort depend on stability?

Radix sort processes the digits of each key one position at a time, and each pass is only meaningful if it preserves the ordering produced by the previous digit. Without a stable pass, the least significant digits sorted earlier would be scrambled and the final order would be wrong.

It is the multi-key idea above, with the digits of a number playing the role of the keys. Take the numbers 329, 457, 657, 839, 436, 720, 355. Sort by the ones digit (stably): 720, 355, 436, 457, 657, 329, 839. Now sort by the tens digit (stably): 720, 329, 436, 839, 355, 457, 657. Finally sort by the hundreds digit (stably): 329, 355, 436, 457, 657, 720, 839. Notice 329 and 355 in the last pass. Both have hundreds digit 3, and they leave the pass in the order the tens pass had left them. That is stability doing the entire job.

The numbers make the appeal clear. Suppose you must sort one million 32-bit unsigned integers. A comparison sort needs on the order of n log2 n comparisons, and log2 of a million is about 19.9, so that is roughly 20 million comparisons. Radix sort with 8-bit digits makes 4 passes, each doing about n work to count and n work to place, plus a 256-slot count array. That is around 8 million element moves in total, with no comparisons at all. The saving is real, but it exists only because each counting pass is stable. The details of the backward scan that makes counting sort stable are laid out on the counting and radix sort page.

How do you make an unstable sort stable?

Attach the original index to every record and use it as the final tiebreaker. Because every index is unique, no two records ever compare as fully equal, so the sort has no ties left to scramble, and any correct algorithm produces the one stable ordering.

decorated = [(rec.key, i, rec) for i, rec in enumerate(records)]
decorated.sort()                 # i is unique, so rec is never compared
result = [rec for _, _, rec in decorated]

The cost is memory and a constant factor. In CPython a two-field tuple costs about 56 bytes, and a three-field one a little more, plus the integer objects for the indices. For a million records you are adding something like 80 MB of overhead that did not exist before. In a language with flat structs, such as C++ or Rust, the same trick costs one 8-byte integer per record, and you can sort a vector of indices instead of moving the records at all.

The other route is to switch tools. C++ offers std::stable_sort, Go offers sort.SliceStable, and Rust offers sort for the stable version and sort_unstable for the faster one. Reaching for the stable variant is usually the better choice than hand-rolling index decoration, because the library version uses a merge-based algorithm designed for the job.

Which languages guarantee a stable sort?

Python has guaranteed a stable sort and sorted since 2.2, and the language documentation promises it. JavaScript made Array.prototype.sort stable in ES2019, so modern engines all agree. Java sorts objects with a stable TimSort, but sorts primitive arrays with a dual-pivot quicksort that is not stable.

That Java split looks inconsistent until you apply the earlier rule: stability is only observable on distinguishable records. Two int values that compare equal are identical, so there is nothing to preserve, and the library is free to pick the faster algorithm. Objects with comparators are distinguishable, so the library pays for stability there. The designers made the same observation I made above and encoded it in the API.

C++ std::sort makes no stability promise, and in practice it is an introsort that will reorder equal elements. Go's sort.Slice is likewise unstable. If you are porting logic between languages, this is a classic source of bugs: code that happened to rely on Python's guarantee gets translated to a language where the default is unstable, and the output differs only on tied inputs. Those inputs are rare in tests and common in production, which is what makes the bug expensive.

When does stability not matter?

It does not matter when the records are indistinguishable once the key matches, or when you want a total order imposed by a composite key anyway. It also stops mattering when you only need a partial result such as the top k, where ties at the boundary are already arbitrary.

I would not pay for stability when sorting plain numbers or strings, or when the comparator already includes every field that could differ. In those cases an unstable sort is both correct and often faster, since it can work in place. Where I would always pay for it is any list that a human looks at and expects to feel consistent: tables, leaderboards, search results, activity feeds. A leaderboard where tied players swap places on every refresh looks broken, even though each snapshot is technically sorted.

Selection problems are a nice contrast. When you take the k most frequent items, as in Top K Frequent Elements, ties at the cutoff can be broken any way the problem allows, so stability buys you nothing. The quicksort family, including the partition trick behind the Dutch national flag problem, deliberately gives stability away in exchange for in-place speed. For the wider performance argument about why that trade usually wins, see why quicksort is faster than merge sort.

Frequently asked questions

Is merge sort always stable?

Only if the merge step prefers the left run when keys are equal. The textbook version does, so it is stable, but a merge written with a strict less-than comparison on the left element would still sort correctly while breaking stability. The guarantee lives in that one tie rule, not in the divide-and-conquer shape.

Is quicksort ever stable?

Yes, but not the in-place version people usually mean. You can write a stable quicksort by partitioning into new lists for smaller, equal and larger elements, which costs O(n) extra space and gives up much of the speed advantage. The standard in-place partitions swap elements across long distances, which is what destroys the order of equal keys.

Does a stable sort have to be slower?

Not necessarily, though it usually needs O(n) extra memory to match O(n log n) time. Timsort is stable and very fast on real data because it exploits existing runs, and it routinely beats unstable sorts on partly ordered input. The honest cost is memory and, for primitives, a slightly higher constant factor.

The next step is to watch stability carry an entire algorithm. Work through counting and radix sort, and try changing the backward scan to a forward one to see exactly where the correctness breaks.