Sub topic 7
Getting Stable Results from an Unstable Sort
This chapter assumes you know what a stable sort is, that you can write a comparator or key function, and that you know quicksort and heapsort are unstable. The examples use C++, but the technique works in any language.
The idea: make every key unique
An unstable sort can reorder elements whose keys are equal. If no two elements have equal keys, there is nothing to reorder, and every correct sort produces the same output. So we make the keys unique by attaching each element's original position, its index in the input, as a final tiebreaker.
The sort then compares by the real key first. Only when two real keys are equal does it compare indexes. Among equal keys, the smaller index comes first, which is exactly the order a stable sort would keep.
Tagging values with their index
std::sort is not guaranteed to be stable. A std::pair compares its first member and, if those are equal, its second. Pairing each key with its index therefore gives the tiebreak with no custom comparator.
#include <algorithm>
#include <cstddef>
#include <iostream>
#include <utility>
#include <vector>
// Sort keys stably using std::sort by breaking ties with the original index.
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()); // pair compares key, then index
std::vector<int> result;
result.reserve(tagged.size());
for (const auto& p : tagged) result.push_back(p.first);
return result;
}
int main() {
for (int k : stable_by_index({3, 1, 3, 2})) std::cout << k << ' ';
std::cout << '\n'; // prints: 1 2 3 3
}With plain integers you cannot see the effect, because equal integers look identical. The technique matters when the values carry other data.
Sorting records through an index array
Copying large records into tagged pairs is wasteful. A cheaper approach sorts a vector of indexes instead and leaves the records where they are. The index itself is the tiebreaker.
#include <algorithm>
#include <cstddef>
#include <iostream>
#include <numeric>
#include <string>
#include <tuple>
#include <vector>
struct Item {
std::string name;
int priority;
};
int main() {
std::vector<Item> items = {{"a", 2}, {"b", 1}, {"c", 2}, {"d", 1}};
std::vector<std::size_t> order(items.size());
std::iota(order.begin(), order.end(), 0); // 0, 1, 2, 3
std::sort(order.begin(), order.end(), [&](std::size_t x, std::size_t y) {
return std::tie(items[x].priority, x) < std::tie(items[y].priority, y);
});
for (std::size_t i : order) std::cout << items[i].name << ' ';
std::cout << '\n'; // prints: b d a c
}std::tie builds tuples of references, and tuples compare left to right. The output matches what std::stable_sort gives for the same input.
Where this is useful
| Situation | Why tag with the index |
|---|---|
| Only an unstable sort exists (some parallel or GPU sort libraries) | It is the only way to get stable order |
| SQL `ORDER BY` on a non-unique column | The database does not promise any order among ties, so add the primary key as the last sort column |
| Rust `sort_unstable_by_key` or Go `sort.Slice` when you want to avoid extra allocation | The cost is an index per element instead of a merge buffer |
| Paginated results | A unique tiebreaker stops rows from moving between pages |
What it costs
Tagging adds one index per element, which is O(n) extra memory, and every comparison does a little more work. The sort's time stays O(n log n). If your library has a stable sort, such as std::stable_sort, sort.SliceStable or Rust's sort, use it instead. It is simpler and harder to get wrong. Tagging is for cases where no stable sort is available or where you need a fully determined order anyway.
Exercise
You sort the records [("x", 5), ("y", 2), ("z", 5), ("w", 2)] by their number with an unstable sort, using (number, original index) as the comparison key. What order do the names come out in, and would the result change if the sort algorithm changed?
Show answer
The order is y, w, x, z. Tagged keys are (5,0), (2,1), (5,2), (2,3), and all of them are distinct, so every correct sort algorithm produces the same order: (2,1), (2,3), (5,0), (5,2).
Exercise
A query uses ORDER BY created_date LIMIT 20 OFFSET 20, and users report that some rows appear on two pages while others never appear. What is the fix?
Show answer
Many rows share a createddate, and the database may order those ties differently each time it runs the query. Add a unique column as the final key, for example ORDER BY createddate, id, so the order is fully determined.