Skip to the solution
EasyDSA9 min read

What is a stable sorting algorithm?

485 views

The problem

Question presented to candidate: "What does it mean for a sorting algorithm to be stable? Give an example where it matters, tell me which common algorithms are stable, and whether the built-in sort in Python is."

What a strong answer should cover:

  • The definition: items with equal keys keep their input order; it only matters when items carry more than the key.
  • Why it matters: multi-key sorting in passes (least important key first), tables with several sort columns, ties in rankings, radix sort.
  • Stable algorithms (insertion, merge, counting, Timsort) versus usually unstable ones (selection, quicksort, heapsort).
  • How to make any sort stable: the original index as a tie-breaker, or a full composite key.
  • Python specifics: list.sort() and sorted() are guaranteed stable (Timsort), so multi-key sorts can be done in passes or with a tuple key, and reverse=True keeps equal items in their original order.

Code / implementation expected: Optional — a multi-key sort with the Python built-in, or a short demonstration of an unstable sort.

  • stability
  • sorting

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

9 min read · 12 sections

Python code

Edit the code and run it here. Each printed line with an expected value becomes a test.

PythonThe built-in stable sort with ties and multiple keys
PythonInsertion sort vs selection sort: stable vs unstable

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 27 of 154 in DSA

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All DSA questions
Up nextEasy

How do you check if a string is a valid palindrome?

Continue