skip to content

What does a stable sort guarantee when you re-sort already-ordered results by a second key?

level: juniorimportance: must knowfreq 75%

answer

  1. think about what happens to ties
  2. two flights with the same price
  3. does the earlier one stay earlier?
  4. chained sorts build multi-key order
  5. equal keys keep their input order

basics

~20 s

A stable sort preserves the input order of records whose keys compare equal. Order flight results by departure time, then sort stably by price, and flights sharing a price stay in time order. That is how multi-key ordering composes.

solid answer

~50 s

Stability is a promise about ties only: two records that compare equal on the sort key come out in the same relative order they went in. That is what makes chained sorting work. Sort a flight-results page by departure time, then run a stable sort by price, and the result is ordered by price with departure time as the tie-break, without ever writing a two-key comparison. Run the second pass with an unstable sort and the price order is still correct, but flights at the same price come out in an arbitrary order — arbitrary but usually deterministic, which is why the bug hides. Stability costs something: the classic stable comparison sorts either buy the guarantee with `O(n)` extra space or with quadratic worst-case work, so it is a property you ask for when ties are observable, not one you assume everywhere.

go deeper

for a junior

Be ready to state in one sentence that equal keys keep their input order, and to give one scenario where that is visible, such as sorting results by one column after another.

for a middle

Explain why chained sorting composes into multi-key order, and be able to contrast that with a single comparison over a key tuple, naming what each approach costs.

for a senior

Show that you treat stability as a stated requirement: name who depends on tie order, and describe how you would pin it with a test so a later algorithm swap cannot silently reorder equal records.

for a principal

Own the call about whether tie order is part of your product contract at all. Committing to it constrains every future sort choice and every data-pipeline rewrite; leaving it unspecified invites downstream code to depend on it accidentally.

## The definition, stated precisely A sorting algorithm is **stable** if, for every pair of records that compare **equal** on the sort key, the record that appeared earlier in the input also appears earlier in the output. It says nothing about records with different keys — those are placed by the ordering itself — and it says nothing about how fast the sort is or how much memory it uses. It is a single, narrow guarantee about ties. The direction of the claim matters. Stability does **not** say the output is unique, does not say the algorithm is deterministic, and does not say equal records are "kept together" in any richer sense than their original relative order. ## Why anyone cares: chained sorting Imagine a flight-results page. The user first orders by departure time, then clicks the price column. Two implementations are possible: 1. **One comparison pass over a key tuple.** Compare price; if equal, compare departure time. Correct, explicit, and independent of the sort's tie behaviour — but you must know all the keys up front. 2. **Chained stable sorts.** Sort by departure time, then sort by price with a **stable** algorithm. The second pass moves records into price order and leaves the earlier arrangement intact among equal prices, so the result is price-major, time-minor. The second approach is what makes interactive, user-driven ordering cheap: each click is one sort by one key, and the accumulated key priority is simply the reverse of the click order. It only works if the sort is stable. Swap in an unstable algorithm and the page still looks sorted — the price column is monotone — but the ordering inside each price bucket is scrambled. This is the classic silent regression: nothing throws, the visible column is right, and the only symptom is a test that asserts a full expected row order failing intermittently as data changes. ## Stability is not determinism The most common wrong answer is "stable means you get the same output every time." A sorting algorithm with no randomness gives the same output for the same input whether or not it is stable; an unstable sort can be perfectly reproducible and still put equal records in an order that has nothing to do with their arrival. The two properties are independent: - *Deterministic* relates one run to another run on the same input. - *Stable* relates the output to the input on a single run. A related trap: an unstable sort's tie order can shift when unrelated parts of the input change, when the input size crosses an implementation threshold, or when the algorithm behind an interface changes. Determinism today is not stability tomorrow. ## When stability buys nothing If equal keys are **indistinguishable** — sorting bare numbers with no payload attached — stability is unobservable, because swapping two equal values produces a result nobody can tell apart. Stability becomes meaningful exactly when a record carries more than its sort key: an identifier, a timestamp, a row of display data. That is also why the guarantee is discussed most in the context of records and objects, and why a fully specified comparison that breaks every tie makes stability moot. ## The cost side Stability is not free, and mainstream runtimes have made visibly different calls about it, which is why the property is worth asking about rather than assuming. Among the classic comparison sorts, insertion sort is stable and needs no buffer but is quadratic in the worst case; merge sort is stable and `O(n log n)` in the worst case but the standard array form needs `O(n)` extra space; the in-place partitioning sorts give up stability in exchange for sorting within the array. So the practical framing is: *do ties need to hold?* If yes, you are choosing between extra memory, extra comparison work (carry the original position as a final tie-break key), or an intricate in-place stable merge. If no, you have a wider menu. ## How to talk about it in an interview Say the definition in one sentence, then immediately give the chained-sort scenario, then name the cost. That order — guarantee, consequence, price — shows you treat stability as an engineering requirement rather than trivia. Finish by noting when it is irrelevant (indistinguishable equal elements, or a comparison that already breaks all ties), which demonstrates you know the boundary of the property and not just its name.

  • If ties keep their input order, does that mean a stable sort is the deterministic one?
    No — the two are independent. Determinism compares one run to another on the same input; stability compares the output to the input within a single run. An unstable sort with no randomness returns the same scrambled tie order every time, which is exactly why the defect survives testing. And a tie order that is stable-looking today can change when the input size or the underlying algorithm changes.
  • When does stability buy you nothing at all?
    When equal elements are indistinguishable — sorting bare values with no attached payload, where exchanging two equal items yields a result nobody can observe. It also buys nothing when your comparison already breaks every tie on a full key tuple, since no two records ever compare equal.
  • How would you get multi-key ordering without relying on stability?
    Compare a key tuple in priority order in a single pass: price first, departure time as the tie-break. That is explicit, one pass instead of two, and immune to a future algorithm swap. The tradeoff is that you must know the full key priority up front, whereas chained stable sorts let a user build the priority interactively, one column click at a time.

Like restacking a pile of paper forms by department without shuffling them: within a department the forms stay in the order they were already in.

saying these in an interview costs you the question

  • Stable means the algorithm is deterministic
  • Stability only matters when sorting numbers
  • Chained sorting works with any sorting algorithm
  • Stability guarantees a unique output ordering
  • Stable sorts are just slower versions of unstable ones

context