Stable vs Unstable Sorting Algorithms
What does 'stable' mean for a sorting algorithm, and why does it matter? Which sorts are stable, and why it matters for multi-key sorting, with examples.
On this page +
Stability is a property that confuses many learners but is genuinely important in practice. A stable sorting algorithm preserves the relative order of elements that compare as equal. This article makes the concept concrete and explains when you must care about it.
A concrete example #
Imagine a list of employees already ordered by name, and you sort them by department. A stable sort keeps everyone in the same department in their original alphabetical-by-name order. An unstable sort might scramble the names within each department. The final order is still 'sorted by department', but the secondary ordering is lost.
Why stability matters #
Stability is what makes multi-key sorting work. To sort a spreadsheet by date and then by category, you sort by the least significant key first, then by the most significant key using a stable sort — and the earlier ordering survives. Databases depend on stable sorts for predictable ORDER BY results across multiple columns.
Which algorithms are stable #
Stable: Bubble, Insertion, Merge, Counting, Radix, and Tim Sort. Unstable: Selection, Quick, Heap, and Shell Sort. Stability is a consequence of how an algorithm moves elements — Selection Sort, for example, swaps distant elements and can leapfrog equal keys. Unstable sorts can usually be made stable by attaching the original index as a tiebreaker, at the cost of extra memory.
Frequently asked questions
Which sorting algorithms are stable? +
Can Quick Sort be made stable? +
Does stability affect performance? +
See it in motion
Watch this algorithm and nine others run step by step, with live pseudocode and comparison counters.
Launch the visualiser
Software engineer at a stealth-stage startup, and previously a front-end engineer for around a year and a half.