Fundamentals

Stable vs Unstable Sorting Algorithms

Updated June 8, 2026 6 min read

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? +
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 9 others run step by step in our free interactive visualizer.

▶ Launch Visualiser

Related articles

← Back to all articles