Sub topic 5
Sorting by Several Keys
This chapter assumes you can write a key function or comparator in Python or Java and that you know what a stable sort is. A stable sort keeps records with equal keys in their input order. Earlier chapters covered that definition. Here we use stability as a tool.
Real data rarely sorts on a single field. A staff directory sorts by last name, then first name. A leaderboard sorts by score descending, then by finish time ascending. You can build this kind of ordering in two ways:
- Successive stable sorts. Sort once per key, from the least significant key to the most significant.
- One composite comparison. Sort once, comparing the primary key first and falling back to later keys only on ties.
Both give the same result when done correctly. They differ in what they require from the sort function, how they handle mixed sort directions, and how easy they are to get wrong.
The Composite Key: One Pass
The most direct approach compares records field by field. In Python, a key function that returns a tuple does this, because tuples compare lexicographically. Python compares the first elements, and only if they are equal does it compare the second elements, and so on.
people = [
("smith", "carl"),
("jones", "dana"),
("smith", "anna"),
("jones", "bob"),
]
by_name = sorted(people, key=lambda p: (p[0], p[1]))
print(by_name)
# [('jones', 'bob'), ('jones', 'dana'), ('smith', 'anna'), ('smith', 'carl')]Java builds the same ordering by chaining comparators. Comparator.comparing sets the primary key, and each thenComparing adds a tiebreaker that runs only when every earlier comparison returned zero.
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]]
}
}A composite comparison does not need a stable sort to get the keyed fields right. If the key covers every field that matters, two records can only tie when they agree on all of those fields, and then their relative order does not affect the visible result. Stability still matters when records that tie on the key differ in other fields, such as an ID you did not include in the key.
Successive Stable Sorts: Several Passes
The second approach sorts the whole list once per key. The order of the passes is the part people get backwards: sort by the least significant key first and the most significant key last.
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')]Here is why it works. After the first pass, the list is in first-name order. The second pass reorders by last name. Within each group of equal last names, a stable sort keeps the elements in the order they had going in, and that order is first-name order. The final pass decides the coarse grouping, and the earlier passes decide the order inside each group.
This method depends entirely on stability. If pass 2 were unstable, it could put smith carl ahead of smith anna and undo pass 1. Use it only with a sort the language guarantees to be stable, such as Python's sort, Java's List.sort on objects, C++ std::stable_sort, or Go's sort.SliceStable.
Why anyone uses several passes
A single composite key is usually simpler, so the multi-pass method needs a reason. There are three common ones:
- Interactive column sorting. In a spreadsheet or data grid, the user clicks "City", then clicks "Name". Each click runs one stable sort on the current rows. The grid ends up sorted by name, with ties in city order, and it never has to remember the click history.
- Mixed directions on keys you cannot negate. Sorting strings in descending order inside a tuple key is awkward. Separate passes with
reverse=Trueavoid the problem. - Keys computed in separate stages. If each key comes from a different expensive lookup, you can sort by each one as it becomes available.
Mixing Ascending and Descending Keys
Suppose the goal is department ascending, salary descending, then name ascending.
With a tuple key, you can flip a numeric field by negating it:
from dataclasses import dataclass
@dataclass
class Employee:
name: str
dept: str
salary: int
staff = [
Employee("ivy", "ops", 70),
Employee("ann", "dev", 90),
Employee("joe", "ops", 70),
Employee("bea", "dev", 80),
Employee("cal", "dev", 90),
]
one_pass = sorted(staff, key=lambda e: (e.dept, -e.salary, e.name))
for e in one_pass:
print(e.dept, e.salary, e.name)
# dev 90 ann
# dev 90 cal
# dev 80 bea
# ops 70 ivy
# ops 70 joeNegation works only for numbers. A string has no negative. The multi-pass version handles any type, because Python's reverse=True still keeps equal elements in their original order:
from operator import attrgetter
passes = list(staff)
passes.sort(key=attrgetter("name")) # least significant
passes.sort(key=attrgetter("salary"), reverse=True) # middle, descending
passes.sort(key=attrgetter("dept")) # most significant
for e in passes:
print(e.dept, e.salary, e.name)
# Same output as the one-pass version.Step through it. After the name pass the order is ann, bea, cal, ivy, joe. The salary-descending pass gives ann 90, cal 90, bea 80, ivy 70, joe 70, and ann stays ahead of cal because the pass is stable. The department pass then groups dev before ops and keeps that order inside each group.
In Java, give the descending direction to that one key only:
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
public class Staff {
record Employee(String name, String dept, int salary) {}
public static void main(String[] args) {
List<Employee> staff = new ArrayList<>(List.of(
new Employee("ivy", "ops", 70),
new Employee("ann", "dev", 90),
new Employee("joe", "ops", 70),
new Employee("bea", "dev", 80),
new Employee("cal", "dev", 90)));
staff.sort(Comparator.comparing(Employee::dept)
.thenComparing(Employee::salary, Comparator.reverseOrder())
.thenComparing(Employee::name));
staff.forEach(e -> System.out.println(e.dept() + " " + e.salary() + " " + e.name()));
}
}Common Errors
Passes in the wrong order
Sorting by the primary key first and the secondary key last produces a list ordered mainly by the secondary key. That is the opposite of what you wanted. If the output looks grouped by the wrong field, check the pass order first.
An unstable sort in one of the passes
Each pass after the first must be stable, or it can scramble the work of the passes before it. Go's sort.Slice, C++ std::sort, and Rust's sort_unstable all make this mistake easy to write. The output often looks right on small test data, because unstable algorithms such as insertion-sort fallbacks happen to keep order on short inputs, and then it fails on larger inputs.
Calling `reversed()` on the whole chain
In Java, .reversed() applies to the entire comparator it is called on:
// Wrong: reverses dept AND salary, giving dept descending.
Comparator<Employee> wrong = Comparator.comparing(Employee::dept)
.thenComparing(Employee::salary)
.reversed();Put the reversal on the single key that needs it, as in the earlier example, using Comparator.reverseOrder() or by reversing an inner comparator before chaining it.
Negation that overflows
Negating a key is safe in Python, where integers have no fixed size. In Java, C++, Go, or Rust, -x on the minimum value of a fixed-width integer type overflows. In Java, -Integer.MIN_VALUE is still Integer.MIN_VALUE. Use a reversed comparator for those languages instead of arithmetic tricks. The same caution applies to comparators written as a - b, which the chapter on comparator contracts covers.
Keys that do not fully separate records
If two records tie on every key, a stable sort keeps their input order and an unstable sort may not. If you need a fixed order that does not depend on the input, for example for reproducible test output, add a unique field such as an ID as the last key.
Choosing an Approach
| Concern | Composite key or comparator | Successive stable sorts |
|---|---|---|
| Requires a stable sort | No, if the key covers every field that matters | Yes, for every pass after the first |
| Number of sort calls | One | One per key |
| Time | One O(n log n) sort, with costlier comparisons | k sorts of O(n log n) each for k keys |
| Mixed directions | Easy for numbers; needs reversed comparators for others | Easy with a stable descending flag |
| Fits incremental UI sorting | Poorly; you must track every active key | Naturally; one stable sort per click |
| Main risk | Misplaced `reversed()`, negation overflow | Wrong pass order, unstable pass |
Use a single composite key or chained comparator by default. It makes one pass and states the full ordering in one place. Reach for successive stable sorts when keys arrive one at a time, as in grid column clicks, or when a stable descending flag is simpler than building a reversed comparator.
Exercise
A list of orders has fields region, date and amount. You want region ascending, then date descending, then amount ascending. Using Python's list.sort with successive passes, give the three calls in the order you would make them.
Show answer
orders.sort(key=attrgetter("amount")), then orders.sort(key=attrgetter("date"), reverse=True), then orders.sort(key=attrgetter("region")). The least significant key goes first and the most significant key goes last, and reverse=True keeps stability for the date pass.
Exercise
A Go program sorts rows by city with sort.Slice and then by country with sort.Slice, expecting country order with cities sorted within each country. On a 10-row test it works; in production it does not. Explain the cause and the fix.
Show answer
sort.Slice is not guaranteed stable, so the country pass may reorder rows that share a country and destroy the city order from the first pass. Small inputs often happen to come out in order because the implementation uses insertion sort on short slices. Use sort.SliceStable for the second pass, or do a single sort whose less function compares country and then city.
Exercise
What order does this Java comparator produce for employees: Comparator.comparing(Employee::dept).thenComparing(Employee::name).reversed()? How would you get dept ascending with name descending?
Show answer
reversed() applies to the whole chain, so it sorts dept descending and, within each dept, name descending. For dept ascending and name descending, write Comparator.comparing(Employee::dept).thenComparing(Employee::name, Comparator.reverseOrder()).