Interview Concept: Stable vs Unstable Sorting Algorithms

Stable vs unstable sorting explained: what stability means, which algorithms are stable, and why it matters when sorting by multiple keys. With a comparison table.

What Is a Stable Sort?

A sort is stable if elements that compare equal keep their original relative order after sorting. If two records have the same key, a stable sort guarantees the one that appeared first in the input still appears first in the output.

Why Stability Matters

  • Sorting by multiple keys: sort by a secondary key first, then a stable sort on the primary key preserves the secondary order.
  • Example: sort people by age, then stably by city — within each city, people stay ordered by age.
  • Databases and spreadsheets rely on stability for predictable multi-column sorting.

Which Algorithms Are Stable?

StableNot stable (by default)
Bubble sortSelection sort
Insertion sortQuick sort
Merge sortHeap sort
Counting sortShell sort
Radix sort (uses stable counting) 

Note: an unstable sort can be made stable by adding the original index as a tie-breaker in the comparison.

Language Defaults

  • Python sort/sorted (Timsort): stable.
  • Java Arrays.sort on objects (Timsort): stable; on primitives (dual-pivot quicksort): not stable.
  • C++ std::sort: not guaranteed stable; use std::stable_sort when you need stability.

Key Takeaways

  • Stability preserves the input order of equal keys.
  • Merge, insertion, counting, and radix sort are stable; quick, heap, and selection are not.
  • Add the original index as a tie-breaker to make any sort behave stably.
  • Reference: CLRS, Ch. 8; Wikipedia, "Sorting algorithm" (stability).
Written by Lorens Mishra

Software Engineer Notes Management System Administrator

Discussion

0 comments
Sign in to join the discussion.

No comments yet. Be the first to say something.