Sub topic 13
What Stability Costs
This chapter assumes you know Big-O notation for time and space, the stability of merge sort and quicksort, and the library functions covered in the previous chapter. Stability is a guarantee, and libraries pay for it in memory, speed, or both. This chapter shows where that cost comes from and when it is worth paying.
Where the Cost Comes From
An unstable algorithm can swap distant elements freely. Quicksort and heapsort do this, which lets them work in place with O(1) or O(log n) extra memory. A stable algorithm must never move an element past an equal one. The simplest efficient way to guarantee that is merging, and merging two sorted halves quickly needs a scratch buffer.
| Approach | Time | Extra memory | Stable |
|---|---|---|---|
| Quicksort / introsort / pdqsort | O(n log n) | O(log n) | No |
| Heapsort | O(n log n) | O(1) | No |
| Merge sort, Timsort | O(n log n) | O(n) | Yes |
| In-place merging (rotations) | O(n log² n) | O(log n) | Yes |
| Block merge sort (e.g. WikiSort) | O(n log n) | O(1) | Yes, with a larger constant factor |
Libraries pick a row from this table. Timsort, used by Python and by Java for object arrays, needs a temporary buffer of up to n/2 elements. C++ std::stable_sort tries to allocate a buffer. If the allocation fails, it falls back to in-place merging, which slows it to O(n log² n). Go's sort.SliceStable never allocates. Its documentation states O(n log n) calls to less but O(n log n log n) swaps.
Measuring the Difference
The gap is easy to see on plain integers, where stability is invisible anyway:
#include <algorithm>
#include <chrono>
#include <iostream>
#include <random>
#include <vector>
template <typename F>
double time_ms(std::vector<int> v, F sorter) {
auto start = std::chrono::steady_clock::now();
sorter(v);
auto end = std::chrono::steady_clock::now();
return std::chrono::duration<double, std::milli>(end - start).count();
}
int main() {
std::mt19937 rng(42);
std::vector<int> data(2'000'000);
for (auto& x : data) x = static_cast<int>(rng());
double unstable = time_ms(data, [](std::vector<int>& v) { std::sort(v.begin(), v.end()); });
double stable = time_ms(data, [](std::vector<int>& v) { std::stable_sort(v.begin(), v.end()); });
std::cout << "std::sort: " << unstable << " ms\n";
std::cout << "std::stable_sort: " << stable << " ms\n";
}Compile with optimizations, for example -O2. The numbers depend on your hardware and standard library. On random data, the unstable sort usually wins because it allocates nothing and stays cache-friendly. On data that is already partly sorted, Timsort-style stable sorts can win, because they find existing runs and merge them in close to linear time.
The Hidden Cost of Forcing Stability
Adding the original index as a tiebreaker makes any sort stable, but it is not free. Each element grows by the size of an index, often 8 bytes, and you usually copy the data into a tagged array and back out. For large records sorted by small keys, a library stable sort is usually cheaper than tagging the elements yourself.
Choosing Deliberately
The most common mistake goes the other way: code relies on stability without asking for it. A program that calls sort.Slice in Go or std::sort in C++ might keep equal elements in order on small test inputs and then fail on production data. If correctness depends on the order of equal elements, call the stable function by name. If it does not, the unstable function gives you less memory use and often more speed.
Exercise
You sort 50 million 64-bit integers on an embedded device with little spare RAM. A colleague suggests std::stable_sort "to be safe." What do you recommend, and why?
Show answer
Use std::sort. Equal integers are indistinguishable, so stability cannot change the result. std::stable_sort would try to allocate a large buffer (hundreds of megabytes here). If that allocation fails, it falls back to O(n log² n) in-place merging, so you pay in memory or in time and gain nothing.
Exercise
A list of 10 million large records must be sorted by a non-unique date field, and records with the same date must keep their input order. Is tagging each record with its index and calling an unstable sort a good choice?
Show answer
Usually not. Tagging adds an index to every element and an extra copy pass, and it does the same job a library stable sort already does, often more efficiently. Call the language's stable sort, such as sorted in Python, List.sort in Java, std::stable_sort in C++, or sort.SliceStable in Go.