Sub topic 2
Sorting by Several Keys
This chapter assumes you know what a stable sort is, can pass a key function or comparator to a sort, and can read Big-O notation.
Two Passes or One Comparator
Suppose you want people ordered by last name and, within each last name, by first name. With a stable sort, you sort by the secondary key first and by the primary key last. The second sort keeps the order from the first sort among people who share a last name.
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')]You can also do it in a single pass with a composite key, such as key=itemgetter(0, 1) in Python or Comparator.comparing(...).thenComparing(...) in Java. Successive sorts are useful when the keys go in different directions, for example ascending by name and then descending by date.
Which Classic Algorithms Are Stable
| Algorithm | Stable | Reason |
|---|---|---|
| Insertion sort | Yes | It shifts only elements that are strictly greater |
| Merge sort | Yes | On ties, it takes from the left half first |
| Quicksort | No | Partitioning swaps elements across long distances |
| Heapsort | No | Building the heap and extracting from it reorders equal keys |
Stability often depends on a single character. If insertion sort tests >= instead of >, it moves elements past equal ones and is no longer stable.
Stable Results from an Unstable Sort
You can pair each key with its original index. Every element is then unique, so any correct sort gives the same order a stable sort would.
#include <algorithm>
#include <cstddef>
#include <utility>
#include <vector>
std::vector<int> stable_by_index(const std::vector<int>& keys) {
std::vector<std::pair<int, std::size_t>> tagged;
tagged.reserve(keys.size());
for (std::size_t i = 0; i < keys.size(); ++i) tagged.emplace_back(keys[i], i);
std::sort(tagged.begin(), tagged.end()); // compares key, then index
std::vector<int> result;
result.reserve(tagged.size());
for (const auto& p : tagged) result.push_back(p.first);
return result;
}The cost is O(n) extra memory for the indices.
Comparators the Library Can Trust
Most libraries require the comparator to be a strict weak ordering. That means three things:
less(a, a)is false.- If
less(a, b)andless(b, c)are both true, thenless(a, c)is true. - Elements that are "equal" (neither is less than the other) form consistent groups.
Exercise
You need to sort orders by customer ascending and, within each customer, by date descending, using only stable sorts. Which sort do you run first?
Show answer
Sort by date descending first, then stably by customer ascending. The last sort sets the primary order, and stability keeps the date order within each customer.