Stable Sorting Algorithms

In short: A stable sorting algorithm keeps items that compare as equal in the same relative order they had in the input. Merge sort, insertion sort, and counting sort are typically stable; quicksort, heapsort, and selection sort typically are not.

A stable sorting algorithm ensures that items that are equal to each other aren't reordered during the sorting process.

For instance, suppose we're sorting an array of computer science majors by their grade point average.

[('Mia', 3.9), ('Andrey', 3.2), ('Yvette', 3.9), ('Theo', 3.5), ('Charlie', 2.7)]

A stable sort will put Mia before Yvette in the sorted array, since Mia is before Yvette in the input.

[('Charlie', 2.7), ('Andrey', 3.2), ('Theo', 3.5), ('Mia', 3.9), ('Yvette', 3.9)]

An unstable sort doesn't offer any guarantees about Mia appearing before Yvette. So its output might look like this:

[('Charlie', 2.7), ('Andrey', 3.2), ('Theo', 3.5), ('Yvette', 3.9), ('Mia', 3.9)]

These sorting algorithms are usually stable:

  • counting sort
  • merge sort
  • insertion sort

These sorting algorithms are usually not stable:

  • quicksort
  • heapsort
  • selection sort

Frequently Asked Questions

What is a stable sort?

A sort is stable if any two items with equal keys come out in the same order they went in. For example, sorting students by GPA keeps students with the same GPA in their original order.

Which sorting algorithms are stable?

Merge sort, insertion sort, counting sort, LSD radix sort, and bubble sort are stable in their standard forms. Quicksort, heapsort, and selection sort are not stable in their usual in-place forms.

Is selection sort stable?

Not in its usual in-place form: swapping the minimum into place can jump an element past an equal one. It can be made stable by shifting items instead of swapping, at extra cost.

Is heap sort stable?

No. Building the heap and repeatedly swapping the root to the end of the array can reorder elements with equal keys.

Why does sort stability matter?

It lets you sort by several keys in passes (sort by name, then stably by department) and it's required inside LSD radix sort, which relies on a stable sort for each digit.

Last updated: October 21, 2026

What's next?

If you're ready to start applying these concepts to some problems, check out our mock coding interview questions.

They mimic a real interview by offering hints when you're stuck or you're missing an optimization.

Try some questions now

. . .