Stability and sort keys
🌍 In real life. The class register lists students in alphabetical order: Ana, Bob, Cy, Dee. After the exam the teacher sorts the register by marks. Ana and Cy both got 80. Which of them comes first?
The fair answer is the order they already had: Ana before Cy, alphabetical. A sort that promises this is called stable. It matters whenever you sort by one thing and want an earlier order to survive among the ties: results by marks with names alphabetical, a train timetable by time with platforms in order, a shop's orders by date with the earliest booking first.
The idea in one sentence: a sort is stable when values that compare equal keep the order they had before sorting, and a sort key is the part of each item the sort compares.
Its words:
- stable sort: equal keys never change their order
- sort key: what the sort compares; here the mark, not the whole (name, mark) pair
- tie: two items with equal keys
- key function:
key=in Python: a function that turns each item into its key
How a sort keeps (or loses) the order of ties:
- insertion and bubble sort swap only neighbours, and only when the left one is strictly bigger
- so an item never jumps over an equal one: ties keep their order, and these sorts are stable
- selection sort swaps the smallest to the front over a long distance
- that jump can carry an item past an equal one: selection sort is not stable
Here are the marks with names, sorted by insertion sort. Ana and Cy keep their order:
Now the same register with selection sort. Its very first swap sends Ana from the front to the back, past Cy:
Why it is correct. Insertion sort moves a key left only while the value on its left is strictly bigger, so it stops right after an equal value, never jumping past it; two equal items are never swapped with each other, so they come out in the order they went in. Selection sort's swap of a[i] with the smallest value can send a[i] far right, past values equal to it, and nothing ever brings it back in front of them.
Sorting by more than one thing. Python's sorted() and list.sort() are stable (Lesson 45.4 shows how). That gives two ways to sort by marks, high to low, with ties in name order:
- one sort with a tuple key:
key=lambda s: (-s[1], s[0]). Tuples compare item by item, so the mark decides first and the name breaks ties - two stable sorts, least important first: sort by name, then by mark; the second sort keeps the names in order among the ties
What it costs. Stability is free for insertion and bubble sort. A key function is called once per item, so it adds n calls: O(n), small next to the sort itself.
results = [("Ana", 80), ("Bob", 70), ("Cy", 80), ("Dee", 60)]
by_mark = sorted(results, key=lambda s: s[1])
print(by_mark) # Ana stays before Cy
best_first = sorted(results, key=lambda s: (-s[1], s[0]))
print([name for name, mark in best_first])
# two stable sorts: the least important key first
two_pass = sorted(results, key=lambda s: s[0])
two_pass.sort(key=lambda s: s[1], reverse=True)
print([name for name, mark in two_pass])Mistakes and edge cases.
key=s[1]:key=needs a function, so writekey=lambda s: s[1]- two sorts in the wrong order: the last sort decides the main order, so sort by the least important key first
-s[0]on a name: you can't negate a string (TypeError: bad operand type for unary -: 'str'); to sort names Z to A, use a separate sort withreverse=Truereverse=Trueis still stable: ties keep their original order, they are not reversed- a tuple key whose later items can't be compared: if two items tie on the first part, Python compares the second; if that is, say, a dict, you get a
TypeError
Quiz
Python's sort is stable. What does this print?
results = [("Ana", 80), ("Bob", 70), ("Cy", 80), ("Dee", 60)] by_mark = sorted(results, key=lambda s: s[1]) print([name for name, mark in by_mark])Which of this chapter's sorts are stable, as written in Lessons 44.1 and 44.2?
- Bubble sort and insertion sort, but not selection sort
- All three
- Only selection sort
What does this print?
words = ["pear", "fig", "kiwi", "apple", "date"] print(sorted(words, key=len))Students are (name, mark) pairs. Which key sorts marks from high to low, with ties in name order, in one sort?
- key=lambda s: (-s[1], s[0])
- key=lambda s: (s[0], -s[1])
- key=lambda s: -s[1] + s[0]
You will sort a list twice with stable sorts, to get it by mark with ties in name order. Which sort goes first?
- By name first, then by mark
- By mark first, then by name
- It doesn't matter
This should list the best marks first, ties in name order: ['Ana', 'Cy', 'Bob', 'Dee']. It prints ['Cy', 'Ana', 'Bob', 'Dee']. Which line is wrong?
results = [("Ana", 80), ("Bob", 70), ("Cy", 80), ("Dee", 60)] best_first = sorted(results, key=lambda s: (s[1], s[0]), reverse=True) print([name for name, mark in best_first])
Coding tasks
Write
rank_students(results):resultsis a list of(name, mark)pairs. Return the names from the highest mark to the lowest; students with the same mark in alphabetical order.Write
stable_by_mark(results)yourself, withoutsortorsorted: return a new list of the(name, mark)pairs ordered by mark from low to high, using insertion sort on the marks only, so students with the same mark stay in the order they were given. Leaveresultsunchanged.