Fundamentals

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.

Aman Jaiman
6 min read
On this page +
  1. In plain English
  2. A concrete example
  3. Why stability matters
  4. Which algorithms are stable
  5. Frequently asked questions

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.

Found this useful?

Share it with someone who is learning this too.

Questions

Frequently asked questions

Which sorting algorithms are stable? +
Merge Sort, Insertion Sort, Bubble Sort, Counting Sort, Radix Sort, and Tim Sort are stable. Quick Sort, Heap Sort, Selection Sort, and Shell Sort are unstable by default.
Can Quick Sort be made stable? +
Yes, but it requires O(n) extra space to track original positions, which defeats Quick Sort's in-place advantage. If you need stability, Merge Sort or Tim Sort are better choices.
Does stability affect performance? +
Not the asymptotic complexity, but stable algorithms sometimes use more memory or do slightly more work to preserve order. The trade-off is usually worth it when correct multi-key ordering is required.

See it in motion

Watch this algorithm and nine others run step by step, with live pseudocode and comparison counters.

Launch the visualiser
Aman Jaiman
Written by
Aman Jaiman

Software engineer at a stealth-stage startup, and previously a front-end engineer for around a year and a half.

Keep reading

Related guides

Link copied