Sub topic 13
What Stability Costs
This chapter assumes you have read the earlier chapters on what stability means, which classic algorithms are stable, and how Timsort, introsort and pattern-defeating quicksort (pdqsort) work. You should also be comfortable with Big-O notation for time and space.
Stability is a guarantee, and every guarantee has a price. A stable sort may not move an element past an equal one. That rule limits which operations the algorithm can use. In practice, you pay for it in one of three ways: extra memory, extra data movement, or giving up optimizations that unstable sorts can use. This chapter looks at each cost, where it appears in real libraries, and when you can safely avoid paying it.
The Memory Cost
Why stable merging wants a buffer
Most fast stable sorts are built on merging. Merging two sorted runs is easy and stable if you can copy one run into a temporary buffer and then write the merged result back into the original space. Without the buffer, you have to rotate blocks of elements around inside the array, which takes more work.
So the standard stable sorts allocate memory:
- Classic top-down merge sort uses O(n) auxiliary space.
- Timsort, used by Python and by Java for object arrays, copies only the smaller of the two runs being merged. That keeps its buffer at n/2 elements at most. It also keeps a small stack of pending runs.
- Rust's
slice::sortallocates an auxiliary buffer that grows with the slice length.slice::sort_unstabledoes not allocate.
Unstable sorts need far less:
- Quicksort and its descendants (introsort, pdqsort) partition in place and need only O(log n) stack space when they recurse into the smaller partition first.
- Heapsort needs O(1) extra space.
Stable sorting without a buffer
Stable sorting in O(1) extra memory is possible. You give up speed or simplicity to get it.
| Approach | Extra memory | Comparisons | Practical notes |
|---|---|---|---|
| Merge sort with buffer | O(n) | O(n log n) | Simple and fast; allocation can fail or be expensive |
| Timsort | up to n/2 elements | O(n log n), O(n) on sorted input | Copies only the smaller run during merges |
| In-place merge by rotation | O(1) or O(log n) stack | O(n log n) | O(n log² n) element moves |
| Block merge sort (WikiSort, GrailSort) | O(1) | O(n log n) | Complex code, larger constant factors |
| Insertion sort | O(1) | O(n²) | Only for small inputs |
| Introsort / pdqsort (unstable) | O(log n) | O(n log n) | Fast, no allocation |
| Heapsort (unstable) | O(1) | O(n log n) | Poor cache behavior |
Two standard libraries take the buffer-free route visibly:
- C++
std::stable_sorttries to get a temporary buffer. If it gets one, the standard requires O(n log n) comparisons. If allocation fails, it falls back to an in-place merge, and the bound becomes O(n log² n). Your code still works, but it runs more slowly. - Go's
sort.Stabledocuments its costs plainly: O(n log n) calls toLessand O(n log n log n) calls toSwap. It sorts small blocks with insertion sort and merges them in place with a rotation-based algorithm (SymMerge). It never allocates, and it pays for that in swaps.
You can measure the Go trade-off directly by counting calls:
package main
import (
"fmt"
"math/rand"
"sort"
)
type counting struct {
data []int
less int
swaps int
}
func (c *counting) Len() int { return len(c.data) }
func (c *counting) Less(i, j int) bool {
c.less++
return c.data[i] < c.data[j]
}
func (c *counting) Swap(i, j int) {
c.swaps++
c.data[i], c.data[j] = c.data[j], c.data[i]
}
func main() {
const n = 100000
base := rand.Perm(n)
unstable := &counting{data: append([]int(nil), base...)}
sort.Sort(unstable)
stable := &counting{data: append([]int(nil), base...)}
sort.Stable(stable)
fmt.Printf("sort.Sort: %9d Less, %9d Swap\n", unstable.less, unstable.swaps)
fmt.Printf("sort.Stable: %9d Less, %9d Swap\n", stable.less, stable.swaps)
}The two functions make a similar number of Less calls. sort.Stable usually makes several times as many Swap calls. If your elements are large structs, each swap copies the whole struct, so that extra movement is where the time goes.
The Speed Cost
Freedoms an unstable sort has
An unstable sort can put an element in any position that is consistent with the ordering. Modern unstable sorts use that freedom heavily:
- Free partitioning. Quicksort swaps elements across long distances in one step. A stable sort cannot do this, because a long swap can jump an element over an equal one.
- Cheap handling of duplicates. pdqsort notices when the pivot equals an element that came before the current partition. It then groups all elements equal to the pivot in one linear pass and never touches them again. Inputs with few distinct keys become close to linear time. A stable sort must keep those equal elements in input order, so it cannot just collapse them into a block.
- Branchless and block partitioning. Techniques such as BlockQuicksort buffer comparison results and do the swaps in batches. This avoids branch mispredictions. These tricks rely on reordering freely.
Where stable sorts win
Stability does not always make a sort slower. Timsort and Rust's stable sort look for runs that are already sorted. On data that is nearly sorted, or that is made of a few sorted pieces joined together, they do close to O(n) work. Many real workloads look like this: appending new rows to a sorted log, or re-sorting after a small update. On those inputs a stable run-adaptive sort can beat a quicksort variant, even though pdqsort also detects some patterns.
The main costs of a stable sort on random data are allocating the buffer and copying elements into and out of it. Here is a C++ benchmark you can run to see the difference on your own machine:
#include <algorithm>
#include <chrono>
#include <iostream>
#include <random>
#include <vector>
template <class F>
double time_ms(F f) {
auto t0 = std::chrono::steady_clock::now();
f();
auto t1 = std::chrono::steady_clock::now();
return std::chrono::duration<double, std::milli>(t1 - t0).count();
}
int main() {
std::mt19937 rng(42);
std::uniform_int_distribution<int> dist(0, 999); // many duplicate keys
std::vector<int> base(1'000'000);
for (auto& x : base) x = dist(rng);
auto a = base;
auto b = base;
double t_sort = time_ms([&] { std::sort(a.begin(), a.end()); });
double t_stable = time_ms([&] { std::stable_sort(b.begin(), b.end()); });
std::cout << "std::sort: " << t_sort << " ms\n";
std::cout << "std::stable_sort: " << t_stable << " ms\n";
std::cout << "same result: " << std::boolalpha << (a == b) << '\n';
}Compile with optimizations turned on, for example g++ -O2 -std=c++17. The last line prints true, because two equal int values cannot be told apart. That observation is the basis of the next section.
When Stability Is Free to Skip
Indistinguishable elements
Stability only matters when two elements compare equal but can still be told apart. With plain integers sorted by their own value, a stable and an unstable sort produce the same output, so the stability guarantee buys nothing. Libraries take advantage of this:
- Java's
Arrays.sortuses dual-pivot quicksort for primitive arrays such asint[]anddouble[], and Timsort for object arrays. - Rust's documentation recommends
sort_unstablewhen stability is not needed. For primitives it is generally faster and never allocates.
Watch for values that compare equal but are not identical:
- Floating-point
-0.0and0.0are equal under<, but they print differently. Java avoids the issue fordouble[]by sorting with a total order that puts-0.0before0.0. - Strings compared case-insensitively, or with a locale collator, can be equal under the comparator but different in their bytes.
- Records sorted by one field are almost always distinguishable by their other fields.
Making ties impossible
If your comparator never returns "equal" for two different elements, stability is irrelevant. Sorting user records by a unique ID is one example. Sorting by (score, id) is another. In these cases you can use the faster unstable sort.
The cost of forcing stability
The earlier chapter on making an unstable sort stable showed index tagging: pair each element with its original position and break ties on the index. It works, but it has a price:
- Each element grows by one index, typically 8 bytes. For small elements, that can double the memory the sort has to move.
- Building the tagged array is itself an O(n) allocation, which removes the main advantage of the unstable sort.
- Each comparison that ties on the key does a second comparison on the index.
Index tagging pays off when the library has no stable sort at all, or when you already need a copy of the data. If the language provides a stable sort, use it instead of tagging.
Choosing Deliberately
Some practical rules follow from this chart:
- If ties are observable and the order matters to the result, use the stable sort. A wrong order is a correctness bug, and memory or speed do not change that.
- If the data is often nearly sorted, a stable run-adaptive sort is often the faster choice anyway.
- For primitive values, or for keys that are unique, choose the unstable sort.
- In JavaScript and Python every built-in sort is stable, so there is no choice to make. In Go, C++ and Rust, the default name you reach for (
sort.Slice,std::sort,sort_unstable) may not be the stable one. Pick deliberately.
Exercise
You sort a Rust Vec<u64> of one million distinct IDs with v.sort(). A colleague suggests v.sort_unstable(). Will the output change, and what do you gain or lose?
Show answer
The output will not change. The IDs are distinct, so there are no ties, and equal u64 values could not be told apart even if there were. sort_unstable avoids allocating the auxiliary buffer and is usually faster on random data. You lose nothing, except possibly speed on input that is already mostly sorted, where the stable run-adaptive sort can do close to linear work.
Exercise
A C++ program calls std::stable_sort on a large vector on a system that is almost out of memory. The program still sorts correctly but runs much slower than in testing. Explain why.
Show answer
std::stable_sort tries to allocate a temporary buffer. When allocation fails, it falls back to an in-place merge, which needs no buffer but has a weaker complexity bound: O(n log² n) instead of O(n log n). The result is still correct and stable, but it takes more work, mostly in element moves.
Exercise
You need a stable order of 10 million small structs (16 bytes each) by a non-unique key, in a language with only an unstable sort. Estimate the extra memory of index tagging with an 8-byte index, and name one alternative.
Show answer
Each tagged element grows from 16 to 24 bytes. Counting the tagged copy, about 240 MB must be allocated and moved instead of sorting the 160 MB in place. An alternative is to implement or import a stable merge sort. Its buffer of up to n elements costs a similar or smaller amount, and it avoids the extra index comparisons. If memory is the real limit, a block merge sort keeps extra memory at O(1).