Mental model
A spreadsheet of orders is sorted by date. You click the "customer" column header to sort by customer. Do each customer's orders stay in date order? If the spreadsheet's sort is stable, yes: orders with the same customer keep the relative order they had before, which was by date. If it is unstable, each customer's orders may come out shuffled, and the earlier sort was wasted.
Stability only matters when elements can compare equal without being identical: two orders with the same customer, two people with the same age, two cards with the same rank. Sorting plain integers, two equal 5s are indistinguishable, so no one can tell whether they swapped.
The lab runs insertion sort. Run the Equal values stay in order preset: the input [5, 2, 5, 1, 2, 5]
labels each duplicate with a letter in input order (5a, 5b, 5c), and the sorted output keeps them in
that order. Then compare with the selection sort lab,
which can carry a later 5 in front of an earlier one with a long-distance swap.
Stability, precisely
A sort is stable if, for every pair of elements x and y that compare equal, x comes before y
in the output whenever x came before y in the input.
"Equal" means equal under the comparison used: if you sort people by age, two different people aged 30
are equal for that sort. Stability is a property of the algorithm as implemented. Insertion sort is
stable because it stops shifting at an element that is <= the key; change that test to < and the
same algorithm becomes unstable. Merge sort is stable because, on a tie, it takes from the left half; take
from the right and it is not.
A single run cannot prove a sort stable (it might get lucky), but one counterexample proves it unstable.
Why it matters: sorting by several keys
To sort employees by department, and by salary within each department, there are two methods:
# 1. One sort with a combined comparison (any sort algorithm works)
sort by (department, salary)
# 2. Successive stable sorts, least significant key FIRST
stable sort by salary
stable sort by department
Method 2 works because the second sort groups by department and, being stable, keeps each group in the salary order produced by the first. Doing the passes in the other order sorts by salary in the end and loses the department grouping. Method 1 is usually simpler in code:
| Language | Combined key | Stable built-in for successive passes |
|---|---|---|
| C# | OrderBy(e => e.Dept).ThenBy(e => e.Salary) |
Enumerable.OrderBy is stable; Array.Sort and List<T>.Sort are not |
| Python | sorted(staff, key=lambda e: (e.dept, e.salary)) |
list.sort and sorted are guaranteed stable |
| Java | list.sort(Comparator.comparing(Employee::dept).thenComparing(Employee::salary)) |
List.sort, Collections.sort, Arrays.sort(Object[]) are guaranteed stable |
| C++ | std::sort with a comparator comparing std::tie(a.dept, a.salary) < std::tie(b.dept, b.salary) |
std::stable_sort; std::sort is not stable |
The successive-pass method is how radix sort works (least significant digit first, each pass a stable counting sort) and how many UIs implement "sort by this column, then that one".
Making any sort stable
Attach each element's original index and use it as the last tie-breaker:
decorated = [(key(x), i, x) for i, x in enumerate(a)]
sort decorated by (key, i) # no two entries compare equal any more
result = [x for (_, _, x) in decorated]
Now no two entries are equal, so stability is irrelevant and any sort, even an unstable one, produces the
stable order. The cost is O(n) extra space for the indices. This is a standard workaround for .NET's
unstable Array.Sort.
In place, precisely
A sort is in place if it needs only a small amount of memory beyond the input array. The usual definitions:
- Strict: O(1) auxiliary space, a few variables. Insertion, selection, bubble and heap sort.
- Common: O(log n) auxiliary space is also accepted, which admits quicksort, whose recursion uses an O(log n) stack when it recurses on the smaller partition first.
Merge sort on arrays is not in place: the standard merge needs an O(n) buffer, which the merge sort lab shows as a second row. In-place merging algorithms exist but are complicated and slower in practice. On linked lists, merge sort needs no buffer, because merging relinks nodes instead of copying them.
In place is about memory, not about whether elements move: an in-place sort moves elements around inside
the array. And "not in place" is not automatically bad: Timsort and std::stable_sort spend up to O(n)
memory precisely to be stable and fast.
The classic sorts, classified
| Algorithm | Stable | Auxiliary space | Time (worst) |
|---|---|---|---|
| Bubble sort | yes | O(1) | O(n²) |
| Insertion sort | yes | O(1) | O(n²), O(n) on sorted input |
| Selection sort | no (long-distance swaps) | O(1) | O(n²) |
| Merge sort (arrays) | yes | O(n) | O(n log n) |
| Quicksort | no (partitioning swaps across the range) | O(log n) stack, O(n) if unbalanced and naively recursive | O(n²), O(n log n) expected |
| Heap sort | no (sift-down reorders equals) | O(1) | O(n log n) |
| Counting sort | yes, as usually written (fill output from the end) | O(n + k) for keys in 0 … k | O(n + k) |
| Radix sort (LSD) | yes (needs stable digit passes) | O(n + base) | O(d · (n + base)) |
The quadratic sorts have their own lesson, and quicksort and heap sort explain where their instability comes from. No comparison sort is known that is stable, strictly in place and O(n log n) worst case and simple: practical libraries pick two of the three (Timsort: stable and O(n log n), up to O(n) memory; introsort: in place and O(n log n), unstable).
To compare the work two stable in-place sorts do on the same array, open bubble sort vs insertion sort.
The built-ins
| Call | Stable? | Notes |
|---|---|---|
C# Array.Sort, List<T>.Sort, Span<T>.Sort |
no (documented) | introsort, in place |
C# Enumerable.OrderBy / ThenBy |
yes (documented) | returns a new sequence, O(n) extra |
Python list.sort(), sorted() |
yes (guaranteed by the language docs) | |
Java Arrays.sort(Object[]), List.sort, Collections.sort |
yes (guaranteed) | |
Java Arrays.sort(int[]) and other primitives |
not specified | stability is unobservable for primitives |
C++ std::sort |
no | |
C++ std::stable_sort, std::ranges::stable_sort |
yes | |
C++ std::partial_sort, std::nth_element |
no |
The built-in sorts lesson explains the algorithms behind these calls.
The teaching implementation
The four listings below are insertion sort from the elementary sorts lesson; the lab highlights the comparison line whenever it compares the key with the element to its left. That line is the one that decides stability: it shifts an element only while it is strictly greater than the key, so an equal element is never jumped over. The listings are checked against the merge sort fixture, which verifies stability, and against each language's stable built-in sort on random inputs.
Common mistakes
- Assuming
Array.Sortorstd::sortis stable because it happened to keep the order in a small test. - Running successive stable sorts in the wrong order: the primary key must be sorted last.
- Calling merge sort in place on arrays.
- Breaking stability by accident:
<instead of<=in a merge's tie rule, or>=instead of>in insertion sort's shift condition. - Comparators that are not consistent (for example, returning "less" for both
a, bandb, a): then no sort, stable or not, has a well-defined result, and Java's TimSort may throwIllegalArgumentException: Comparison method violates its general contract.
Edge cases
- All elements distinct under the comparison: every correct sort gives the same output, so stability cannot be observed.
- All elements equal: a stable sort returns the input unchanged.
- Sorting by a key that maps many elements to the same value (e.g.
len): stability decides the order within each group.
Worked practice
1. Sort the cards [7♠, 3♥, 7♥, 3♠, 5♦] by rank with a stable sort. Then with selection sort (select the minimum, swap it to the front). Are the results the same?
Answer
Stable: [3♥, 3♠, 5♦, 7♠, 7♥]. Selection sort: swap 3♥ with 7♠ → [3♥, 7♠, 7♥, 3♠, 5♦]; the minimum of
the rest is 3♠ at index 3, swap with 7♠ → [3♥, 3♠, 7♥, 7♠, 5♦]; then 5♦ swaps with 7♥ →
[3♥, 3♠, 5♦, 7♠, 7♥]. Here the result happens to match, because the second swap put 7♠ back in
front. Try [5♠, 5♥, 3♦]: the first swap gives [3♦, 5♥, 5♠], an unstable result.
2. You need students ordered by grade (descending), and alphabetically by name within each grade, using only stable sorts. In which order do you sort?
Answer
First by name (ascending), then by grade (descending). The last pass is the primary key.
3. Is heap sort in place? Is it stable?
Answer
In place (O(1) extra: the heap lives in the array itself), but not stable: sifting moves elements across long distances and can reorder equal keys.
4. Why is merge sort on a linked list in place, but not on an array?
Answer
Merging two lists only relinks next pointers; no element is copied, so no buffer is needed (only the
O(log n) recursion stack, or O(1) bottom-up). Merging two array halves needs somewhere to put elements
while both halves are still being read.
Summary
- Stable: equal elements keep their input order. It matters only when equal elements are distinguishable.
- Successive stable sorts, least significant key first, give a multi-key order; a combined comparison does it in one pass.
- Any sort becomes stable with the original index as a tie-breaker.
- In place: O(1) (strictly) or O(log n) extra space. Merge sort on arrays is not in place.
- Guaranteed stable: Python's sort, Java's object sorts, C#'s
OrderBy, C++'sstd::stable_sort. Not stable: C#'sArray.Sort, C++'sstd::sort.