Sub topic 2
Keys, Comparators and Equal Elements
This chapter assumes you can write a lambda or pass a function as an argument, and that you know what a record or struct is. It covers how a sort decides that one element comes before another, and why two elements can count as "equal" to the sort while still being different records. That gap between equal-to-the-sort and identical is what the next chapter, on stability, is about.
What the Sort Actually Sees
A comparison sort never looks at your data directly. It only asks one question about two elements, over and over: which of these goes first? You answer that question in one of two ways.
- A key function maps each element to a value that already has a natural order, such as a number or a string. The sort then compares keys.
- A comparator takes two elements and reports their order directly, either as a boolean ("is
aless thanb?") or as a three-way result (negative, zero, or positive).
Anything outside the key or the comparator's logic stays invisible to the sort. If you sort employee records by salary, the names, IDs and start dates simply travel along with each element. The sort cannot use them to break ties.
Key Functions
A key function is called once per element. Python's sorted and list.sort compute every key up front and then compare the cached keys, so an expensive key such as parsing a date string runs only n times, not O(n log n) times.
words = ["pear", "fig", "plum", "kiwi", "date"]
print(sorted(words)) # ['date', 'fig', 'kiwi', 'pear', 'plum']
print(sorted(words, key=len)) # ['fig', 'pear', 'plum', 'kiwi', 'date']
print(sorted(words, key=lambda w: w[-1]))
# ['pear', 'fig', 'plum', 'date', 'kiwi']In the second call, four words have length 4. The key function gives the sort no way to tell them apart, so the sort treats them as equivalent. The order you see among them, pear, plum, kiwi, date, matches their input order. That happens because Python's sort is stable, a property the next chapter defines. Nothing in key=len asked for it.
Keys can be tuples, which compare element by element. That gives you a quick way to break ties on purpose:
words = ["pear", "fig", "plum", "kiwi", "date"]
print(sorted(words, key=lambda w: (len(w), w)))
# ['fig', 'date', 'kiwi', 'pear', 'plum']Now no two words are equivalent, because the tuple keys (4, 'date') and (4, 'pear') differ.
Comparators
Some orderings are awkward to express as a single key, or the language's API is built around comparators. C++ uses a boolean "less than" predicate. Java, JavaScript and Rust use a three-way result.
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
struct Task {
std::string name;
int priority;
};
int main() {
std::vector<Task> tasks = {{"write", 2}, {"test", 1}, {"ship", 2}, {"plan", 1}};
auto by_priority = [](const Task& a, const Task& b) {
return a.priority < b.priority;
};
std::sort(tasks.begin(), tasks.end(), by_priority);
for (const auto& t : tasks) std::cout << t.priority << ' ' << t.name << '\n';
// Priorities print as 1, 1, 2, 2.
// The order of "test"/"plan" and of "write"/"ship" is unspecified.
}With a less-than predicate, the sort learns that a and b are equivalent when less(a, b) and less(b, a) both return false. test and plan both have priority 1, so the predicate returns false in both directions. std::sort may put them in either order, and the order can change between compilers, library versions or input sizes.
Java's three-way comparator reports equivalence directly by returning zero:
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
public class Main {
record Task(String name, int priority) {}
public static void main(String[] args) {
List<Task> tasks = new ArrayList<>(List.of(
new Task("write", 2), new Task("test", 1),
new Task("ship", 2), new Task("plan", 1)));
Comparator<Task> byPriority = Comparator.comparingInt(Task::priority);
tasks.sort(byPriority);
System.out.println(tasks);
// [Task[name=test, priority=1], Task[name=plan, priority=1],
// Task[name=write, priority=2], Task[name=ship, priority=2]]
System.out.println(byPriority.compare(tasks.get(0), tasks.get(1))); // 0
}
}The comparator returns 0 for test and plan even though test.equals(plan) is false. Inside the sort, equivalence is the only kind of "equal" that counts.
Python can still use a comparator by wrapping it with functools.cmp_to_key:
from functools import cmp_to_key
def by_length_then_reverse_alpha(a, b):
if len(a) != len(b):
return len(a) - len(b)
return (a < b) - (a > b) # reverse alphabetical: -1, 0 or 1
words = ["pear", "fig", "plum", "kiwi", "date"]
print(sorted(words, key=cmp_to_key(by_length_then_reverse_alpha)))
# ['fig', 'plum', 'pear', 'kiwi', 'date']A comparator runs on every comparison, roughly n log n times. A key function runs n times. When either one works, prefer the key function in Python.
The Shapes Comparators Take
| Language | Usual form | Signals "equivalent" by | Key-function shortcut |
|---|---|---|---|
| Python | `key=` function | equal keys | built in; `cmp_to_key` for comparators |
| Java | `Comparator.compare(a, b)` returns int | returning 0 | `Comparator.comparing(...)` |
| C++ | `bool less(a, b)` | false in both directions | projections in `std::ranges::sort` |
| JavaScript | `(a, b) => number` | returning 0 | none; write `(a, b) => key(a) - key(b)` |
| Rust | `Fn(&T, &T) -> Ordering` | `Ordering::Equal` | `sort_by_key`, `sort_by_cached_key` |
| Go | `less(i, j int) bool` on indices | false in both directions | `slices.SortFunc` takes a three-way `cmp` |
Each form encodes the same information: a strict ordering between elements, plus a well-defined notion of "neither comes first".
Equivalent Is Not Identical
This distinction matters for the rest of the tutorial. Two elements are equivalent under a sort when the ordering treats neither as smaller. They are identical when they are the same value in every field.
- If you sort plain integers with the default order, equivalent elements are identical. Swapping two 7s changes nothing you can observe.
- If you sort records by one field, equivalent elements usually differ in other fields. Swapping two tasks with priority 2 produces a visibly different list.
So "where do equivalent elements end up?" is a meaningful question only when they carry a payload, meaning fields the sort does not compare. Most real sorts carry a payload: rows in a table, events in a log, objects in a UI list. A sort that leaves the payload order unspecified, like std::sort above, can give output that looks fine in testing and then shuffles rows differently in production.
Common Errors
Inconsistent key and intent. Sorting names with key=str.lower makes "Apple" and "apple" equivalent. That is usually what you want, but it also means their relative order now depends on the sort's tie behavior.
Subtraction comparators. (a, b) -> a - b in Java or C overflows when the values are far apart, for example Integer.MIN_VALUE and 1, and returns the wrong sign. Use Integer.compare or Comparator.comparingInt. In JavaScript, x.p - y.p is safe for ordinary numbers but returns NaN if a field is missing.
Using <= in a less-than predicate. In C++, return a.priority <= b.priority; says every element is less than itself. That breaks the predicate's contract and can cause undefined behavior, including reads past the end of the range. Chapter 8 covers the full set of rules a comparator must obey.
Mutating keys during a sort. If a key depends on state that changes while the sort runs, the sort sees contradictory answers. Compute keys from data that stays fixed for the whole call.
Reversing with a negated key on non-numbers. key=lambda r: -r.score works for numbers but not for strings. Use reverse=True in Python or .reversed() on a Java comparator instead. Python's reverse=True still keeps equivalent elements in their original order. It does not simply flip the output.
Choosing Between a Key and a Comparator
Use a key function when the order is "sort by this derived value", including tuples of values. Keys are harder to get wrong because the key type's built-in order already obeys the rules. In Python and Rust they can also be cheaper, since keys can be computed once.
Use a comparator when the order mixes directions per field (ascending by one, descending by another, on non-numeric data), when it depends on context such as a locale collator, or when the API requires one, as in C++ std::sort and Go's sort.Slice. Build comparators from library combinators like Comparator.comparing(...).thenComparing(...) or Rust's Ordering::then_with where you can, because hand-written comparison chains are where sign and tie bugs creep in.
Exercise
Using Python's sorted(records, key=lambda r: r[1]) on records = [("x", 2), ("y", 1), ("z", 2)], which records are equivalent under the sort, and are they identical?
Show answer
("x", 2) and ("z", 2) are equivalent because both have key 2. They are not identical, because their first fields differ. The key function gives the sort no information to order them, so their relative order depends on how the sort handles ties.
Exercise
A C++ developer writes the predicate [](const Task& a, const Task& b) { return a.priority <= b.priority; } for std::sort. What is wrong with it, and how should it be fixed?
Show answer
The predicate returns true when both tasks have the same priority, including when a task is compared with itself. std::sort requires a strict ordering in which less(a, a) is always false, so this predicate can produce undefined behavior. Fix it by using a strict < : return a.priority < b.priority;
Exercise
Rewrite the Java comparator (a, b) -> a.score() - b.score() so that it cannot overflow, and say which values would have broken the original.
Show answer
Use Comparator.comparingInt(Task::score) or (a, b) -> Integer.compare(a.score(), b.score()). The subtraction overflows when the scores are far apart. For example, a.score() = Integer.MIN_VALUE and b.score() = 1 wraps around to a large positive result, so the comparator reports a > b when a is actually smaller.