Sub topic 7
Getting Stable Results from an Unstable Sort
This chapter assumes you can read Python, C++, Rust and Go at a basic level. You should know what a comparator and a key function are, and what stability means: equal keys keep their input order. It also assumes you know that quicksort and heapsort are not stable.
Sometimes the only sort available is unstable. The fastest sort in your library may be unstable, you may be using a heap or priority queue, or you may be sending an ORDER BY to a database that promises nothing about ties. In all of these cases you can still get exactly the output a stable sort would give. The technique is to make sure no two elements ever compare as equal.
The Core Idea: Remove the Ties
An unstable sort can only scramble elements that it considers equal. If the comparator never reports a tie, the output order is fully determined by the comparator, and the algorithm's internal behaviour stops mattering.
So you add a tiebreaker. Each element gets tagged with its original position, and the comparison becomes "compare by key; if the keys are equal, compare by original position." Two different elements cannot have the same position, so ties are gone. Among equal keys, the element that came first in the input sorts first. That is the definition of a stable result.
This is often called decorate–sort–undecorate:
- Decorate: pair each element with its index (and, optionally, its precomputed key).
- Sort: use any sort, stable or not, comparing
(key, index). - Undecorate: strip the tags off and keep the elements.
Worked Example in Python with a Heap
Python's sorted is already stable, but heapq is not. Popping everything from a binary heap is heapsort, and heapsort reorders equal elements. Tagging each entry with its index fixes this:
import heapq
records = [("alice", 3), ("bob", 1), ("carol", 3), ("dave", 2)]
# Decorate: (key, original index, record)
heap = [(rec[1], i, rec) for i, rec in enumerate(records)]
heapq.heapify(heap)
# Sort and undecorate in one pass
result = [heapq.heappop(heap)[2] for _ in range(len(heap))]
print(result)
# [('bob', 1), ('dave', 2), ('alice', 3), ('carol', 3)]The index does a second job here. Without it, two entries with score 3 would make Python fall back to comparing the records themselves. If the records were dictionaries or other objects without an ordering, that comparison would raise TypeError. Because indices are unique, the comparison always stops at the index, and the third tuple field is never compared. The heapq documentation recommends this same pattern for priority queues.
C++: Sorting a Permutation of Indices
In C++, std::sort is unstable (it is usually introsort). One clean approach is to sort indices into the original vector rather than the records themselves:
#include <algorithm>
#include <cstddef>
#include <iostream>
#include <numeric>
#include <string>
#include <vector>
struct Item {
std::string name;
int priority;
};
int main() {
std::vector<Item> items = {{"a", 2}, {"b", 1}, {"c", 2}, {"d", 1}};
// Decorate: the indices 0..n-1 are the tags.
std::vector<std::size_t> order(items.size());
std::iota(order.begin(), order.end(), 0);
// Unstable sort, but the comparator never reports a tie.
std::sort(order.begin(), order.end(), [&](std::size_t x, std::size_t y) {
if (items[x].priority != items[y].priority)
return items[x].priority < items[y].priority;
return x < y; // original position breaks ties
});
// Undecorate: build the output in sorted order.
std::vector<Item> sorted;
sorted.reserve(items.size());
for (std::size_t i : order) sorted.push_back(items[i]);
for (const auto& it : sorted) std::cout << it.name << ' ';
std::cout << '\n'; // prints: b d a c
}Sorting indices has a side benefit. The sort moves only size_t values, which are cheap to swap, and never moves the heavier Item objects. The permutation in order can also be reused to reorder parallel arrays that belong to the same records.
An alternative is to sort std::pair<Key, std::size_t> values directly. std::pair compares lexicographically, so it compares the key first and the index second without a custom comparator.
Rust and Go
Rust's sort_unstable_by_key avoids allocating a buffer and is often faster than the stable sort_by_key. Tagging with the index gives you stable output from it:
fn main() {
let v = vec![("a", 2), ("b", 1), ("c", 2), ("d", 1)];
let mut tagged: Vec<(usize, (&str, i32))> = v.into_iter().enumerate().collect();
tagged.sort_unstable_by_key(|&(i, (_, k))| (k, i));
let result: Vec<(&str, i32)> = tagged.into_iter().map(|(_, x)| x).collect();
println!("{:?}", result); // [("b", 1), ("d", 1), ("a", 2), ("c", 2)]
}Note that the decorated vector costs O(n) extra memory. That removes the memory advantage of sort_unstable. In Rust you would normally just call sort_by_key. The pattern matters more when the unstable operation is the only one on offer, for example select_nth_unstable or a BinaryHeap.
Go needs more care because sort.Slice passes the comparator the current positions i and j, not the original ones:
package main
import (
"fmt"
"sort"
)
type Person struct {
Name string
Age int
}
type tagged struct {
p Person
idx int
}
func main() {
people := []Person{{"ann", 30}, {"bob", 25}, {"cat", 30}, {"dan", 25}}
t := make([]tagged, len(people))
for i, p := range people {
t[i] = tagged{p, i} // store the original index in the element
}
sort.Slice(t, func(i, j int) bool {
if t[i].p.Age != t[j].p.Age {
return t[i].p.Age < t[j].p.Age
}
return t[i].idx < t[j].idx
})
for i := range t {
people[i] = t[i].p
}
fmt.Println(people) // [{bob 25} {dan 25} {ann 30} {cat 30}]
}Common Mistakes
| Mistake | Why it fails | Fix |
|---|---|---|
| Tiebreaking on current position (`i < j` in Go, or comparing addresses `&a < &b` in C++) | Positions and addresses change as the algorithm moves elements | Store the original index inside the element, or sort indices |
| Capturing the index after an earlier unstable step | The tag records an order that has already been scrambled | Tag at the point whose order you want to preserve |
| Reversing the whole comparator for descending order | The index comparison is reversed too, so later elements win ties | Reverse only the key comparison; keep the index ascending |
| Comparing index before key | Output is sorted by position, which is just the input order | Key first, index last |
| Using a narrow index type (for example 16-bit) | It overflows on large inputs, and the tags stop being unique | Use `size_t`, `usize`, or `int` sized for the input |
The descending case catches many people. To sort by priority from high to low while keeping input order among ties, the comparator is:
#include <cstddef>
struct Tagged {
int priority;
std::size_t idx;
};
bool descending_stable(const Tagged& a, const Tagged& b) {
if (a.priority != b.priority) return a.priority > b.priority; // key reversed
return a.idx < b.idx; // index still ascending
}Python's sorted(..., reverse=True) handles this for you. The documentation states that reverse=True keeps the sort stable, so equal elements stay in input order. Negating the key with key=lambda r: -r[1] does the same for numbers.
Where This Pattern Is Necessary
When a stable sort is available, prefer it. The pattern is necessary where no stable option exists:
- Priority queues and heaps.
std::priority_queue, Python'sheapq, Rust'sBinaryHeapand Java'sPriorityQueueall give FIFO order among equal priorities only if you add an insertion counter. - Selection and partial sorts.
std::partial_sort,std::nth_elementand Rust'sselect_nth_unstablehave no stable versions. - Databases. SQL does not define the order of rows that tie under
ORDER BY. Paginated queries can then show a row twice or skip it across pages. Append a unique column:ORDER BY score DESC, id ASC. Hereidplays the role of the index. - Parallel and GPU sorts. Many high-throughput sort libraries offer only unstable sorts, or run their unstable sorts much faster.
What It Costs
Decoration adds one index per element, which is O(n) extra memory, and comparisons get slightly more expensive when keys are equal. Big-O time does not change: an O(n log n) unstable sort stays O(n log n). Library stable sorts such as merge sort and Timsort usually allocate an O(n) buffer anyway, so decorating an unstable sort is rarely a memory win over calling the stable sort directly. Use the pattern for the guarantee it provides where no stable sort exists, not as a speed trick.
Exercise
A C++ developer writes std::sort(v.begin(), v.end(), [](const Rec& a, const Rec& b) { return a.key < b.key || (a.key == b.key && &a < &b); }); to get stable output. Why is this wrong, and what should they do instead?
Show answer
The comparator compares the addresses of the two elements, and those addresses are their current slots in the vector. The sort moves elements between slots, so the tiebreak changes as the sort runs. It does not reflect input order and can even break the comparator's consistency requirements. They should store an original index in each Rec (or sort a vector of indices) and break ties on that index, or call std::stable_sort.
Exercise
You need to sort tasks by priority from highest to lowest with an unstable sort, keeping input order among tasks with the same priority. Each task is tagged as (priority, index). Write the comparison rule.
Show answer
Compare priority descending first: if a.priority != b.priority, return a.priority > b.priority. Otherwise return a.index < b.index. Only the key comparison is reversed. The index stays ascending, so earlier tasks still win ties.
Exercise
A paginated API runs SELECT * FROM posts ORDER BY score DESC LIMIT 20 OFFSET 40. Users report seeing some posts on two pages and never seeing others. Explain the cause and the fix.
Show answer
Many posts share the same score, and SQL does not define the order of tied rows. The database can return ties in a different order for each query, so page boundaries move. Add a unique tiebreaker column, for example ORDER BY score DESC, id ASC. This makes the order total and gives the same result on every run.