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()andsorted()are guaranteed stable (Timsort), so multi-key sorts can be done in passes or with a tuple key, andreverse=Truekeeps 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.