Sub topic 5
Sorting by Several Keys
This chapter assumes you already know what a stable sort is and how key functions and comparators work. Both were covered in earlier chapters. The examples use Python and Java, but the same ideas apply in any language.
Real data often needs more than one sort key. A staff list might be ordered by last name, and then by first name among people who share a last name. The first key is the primary key. The keys that break ties are secondary keys. You can build this order in two ways: run several stable sorts in a row, or run one sort with a composite comparator.
Approach 1: Successive Stable Sorts
Sort by the least important key first and by the most important key last. Each pass must be stable.
from operator import itemgetter
people = [
("smith", "anna"),
("jones", "bob"),
("smith", "carl"),
("jones", "dana"),
]
people.sort(key=itemgetter(1)) # secondary key first: first name
people.sort(key=itemgetter(0)) # primary key last: last name
print(people)
# [('jones', 'bob'), ('jones', 'dana'), ('smith', 'anna'), ('smith', 'carl')]After the first pass, the list is in first-name order. The second pass groups the list by last name. Within each last-name group, the second pass sees equal keys, so stability keeps them in the order the first pass left them, which is first-name order.
This approach is useful when each key needs a different direction. Python's reverse=True keeps equal elements in their original order, so you can sort descending on one key and ascending on another:
scores = [("ann", 90), ("bob", 85), ("cat", 90), ("dan", 85)]
scores.sort(key=lambda r: r[0]) # name ascending
scores.sort(key=lambda r: r[1], reverse=True) # score descending
print(scores)
# [('ann', 90), ('cat', 90), ('bob', 85), ('dan', 85)]Approach 2: One Composite Comparator
The alternative is a single sort whose comparison looks at every key in turn. In Python, a tuple key does this, because tuples compare element by element:
people.sort(key=lambda p: (p[0], p[1]))In Java, Comparator.comparing and thenComparing build the same chain:
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
public class Main {
record Person(String last, String first) {}
public static void main(String[] args) {
List<Person> people = new ArrayList<>(List.of(
new Person("smith", "carl"),
new Person("jones", "dana"),
new Person("smith", "anna"),
new Person("jones", "bob")));
people.sort(Comparator.comparing(Person::last)
.thenComparing(Person::first));
System.out.println(people);
// [Person[last=jones, first=bob], Person[last=jones, first=dana],
// Person[last=smith, first=anna], Person[last=smith, first=carl]]
}
}The comparator settles any tie on last by comparing first. Because the comparator itself orders by every key, this approach works even with an unstable sort. Stability only matters for elements that are equal on all the keys.
Choosing Between Them
| Situation | Better choice |
|---|---|
| Keys need mixed directions and cannot be negated (such as strings descending) | Successive stable sorts |
| Data is already sorted by the secondary key | One stable sort by the primary key |
| Large data, many keys | Composite comparator (one pass) |
| Only an unstable sort is available | Composite comparator |
In Java you can also reverse a single key with .thenComparing(Person::first, Comparator.reverseOrder()), so mixed directions do not always require multiple passes.
Common Errors
- Running the passes in the wrong order, as described in the warning above.
- Using successive sorts with an unstable function, such as
std::sortor Go'ssort.Slice. The second pass can scramble the order the first pass produced. - Negating a key to reverse it when the key is not numeric. In Python,
-nameraises aTypeErrorfor a string.
Exercise
You have a list of orders as (customer, date) tuples. You want customers in alphabetical order, and each customer's orders with the newest date first. Using two calls to Python's list.sort, which key do you sort by first, and which call takes reverse=True?
Show answer
First sort by date with reverse=True, so the newest orders come first. Then sort by customer with no reverse. The second (last) pass sets the primary key, and stability keeps the newest-first date order within each customer.
Exercise
A colleague runs C++ std::sort by first name and then std::sort by last name. The output is sometimes out of first-name order inside a last-name group. Why does this happen, and what are two ways to fix it?
Show answer
std::sort is not stable, so the second pass may reorder elements whose last names are equal. One fix is to use std::stable_sort for both passes. The other is to make a single std::sort call with a comparator that compares last name and then first name.