Stable Sorting
in Python
Understand why order preservation matters when sorting, how Python's built-in sort guarantees stability, and when it changes the outcome of your programs.
What Does Sorting Really Mean?
Sorting rearranges a collection of items into a defined order: alphabetical, numerical, by date, by priority, and so on. In Python you use sorted() or list.sort() every day.
But what happens when two items compare as equal? For example, two students with the same grade, or two products at the same price. The answer depends on whether your sorting algorithm is stable.
Defining Stable Sorting
Why Does Stability Matter?
Imagine a spreadsheet of student records already sorted by name. You then sort by grade. With a stable sort, students sharing the same grade remain in alphabetical order. With an unstable sort, the alphabetical order within each grade is destroyed.
The Formal Definition
In plain language: equal elements never swap positions relative to each other. The original ordering is preserved within each group of ties.
This is a property of the algorithm, not the data. Some algorithms are inherently stable (Merge Sort, Insertion Sort, Timsort). Others are inherently unstable (Quicksort, Heapsort) unless modified.
Visualising Stability
Python Uses Timsort
Python's sorted() and list.sort() both use Timsort, a hybrid sorting algorithm created by Tim Peters in 2002. Timsort combines Merge Sort and Insertion Sort. Its key properties:
Stable vs Unstable Algorithms
| Algorithm | Stable? | Time (avg) | Used In |
|---|---|---|---|
| Timsort | ✓ Yes | \( O(n \log n) \) | Python, Java |
| Merge Sort | ✓ Yes | \( O(n \log n) \) | General use |
| Insertion Sort | ✓ Yes | \( O(n^2) \) | Small arrays |
| Quicksort | ✕ No | \( O(n \log n) \) | C stdlib |
| Heapsort | ✕ No | \( O(n \log n) \) | Embedded |
The Power of Multi-Key Sorting
Because Python's sort is stable, you can sort by multiple criteria by sorting multiple times: sort by the least important key first, then by the most important key last.
How to Apply Stable Sorting
Example 1: Sorting Tuples
We sort only by the number (index 0). The two items with key 3 are (3, "banana") and (3, "apple").
Example 2: Two-Pass Sort
Example 3: Tuple Key Shortcut
Instead of two passes, you can sort once using a tuple key. Python compares tuples element-by-element, giving you multi-key sorting in one step:
When Stability Doesn't Matter
Stability is irrelevant in certain situations. Recognising these cases helps you avoid over-engineering:
Common Mistakes
Summary at a Glance
| Concept | Key Point |
|---|---|
| Stable Sort | Equal elements keep their original relative order |
| Python's sort | Timsort: always stable, \( O(n \log n) \) worst case |
| Multi-key sorting | Sort least-important key first, most-important last |
| Tuple key | key=lambda x: (primary, secondary) in one pass |
| When irrelevant | Unique keys or single-criteria sorts |
| Unstable sorts | Quicksort, Heapsort: may swap equal elements |
Question 1 of 5
A sorting algorithm is called stable when:
Question 2 of 5
Given the input [(2,"x"), (1,"y"), (2,"z")], what is the result of sorted(data, key=lambda t: t[0])?
Question 3 of 5
To sort a list first by department (primary) then by hire date (secondary) using two successive sort() calls, which order should you sort in?
Question 4 of 5
Which of the following algorithms is NOT stable?
Question 5 of 5
When does stability have no observable effect on the sorted output?