Stable vs Unstable Sorting
A sort is stable when records with equal keys come out in the same order they went in. An unstable sort may reorder them. The difference is invisible on plain numbers and decisive on records: it decides whether a table sorted by name stays alphabetical inside each group after you sort it by score.
What Stability Means
Sorting compares records by a key, such as a score, and ignores the rest of each record. When two records have the same key, the sort could put either one first. A stable sorting algorithm always keeps them in the order they had in the input. An unstable sorting algorithm makes no such promise: tied records may come out in any order, and the order can even change between runs or library versions.
Take six people listed alphabetically, Ana 2, Ben 3, Cal 2, Dee 1, Eve 3, Fay 1, and sort them by score. A stable sort must output Dee Fay Ana Cal Ben Eve: within each score, the names stay alphabetical because that was their input order. Selection sort outputs Dee Fay Cal Ana Eve Ben. The scores are just as sorted, but two tied pairs swapped places.
Stability is about the parts of a record the sort did not look at. Sort plain integers and the question disappears: two 5s are identical, so no one can tell which came first. That is why some libraries use an unstable sort for numbers and a stable one for objects.
- Stable: if a and b have equal keys and a came first, a still comes first
- Both kinds produce correctly sorted keys; they differ only on ties
- No ties in the keys means no difference at all
Which Sorts Are Stable, and Why
The rule of thumb: a sort is stable if a record only ever moves past records with strictly larger (or smaller) keys, never past an equal one. Insertion sort shifts a record left while the neighbour is greater, and stops at an equal neighbour. Merge sort, when the two front values are equal, takes the one from the left half first. Both keep ties in order.
A sort is unstable when it moves a record a long way in one swap. Selection sort swaps the minimum into place and throws the displaced record to a far position, over everything in between, including its own ties. Quick sort's partition and heap sort's sift-down do the same. Nothing about their comparisons is wrong; the swaps simply do not check what they jump over.
Stability lives in the code, not only in the name. Write insertion sort's shift test as >= instead of > and equal records slide past each other, reversing every tie. Write merge with < instead of <= when choosing the left value and merge sort turns unstable too.
| Sort | Stable? | Reason |
|---|---|---|
| Insertion sort | Yes | Shifts only past strictly greater values |
| Bubble sort | Yes | Swaps neighbours only when they are out of order |
| Merge sort | Yes | On a tie, takes from the left half first |
| Counting and radix sort | Yes | Places values back in input order within each key |
| Selection sort | No | A long swap throws a value past its equals |
| Quick sort | No | Partition swaps across the range |
| Heap sort | No | Sifting moves values across the heap |
- Python's sort and sorted, Java's sort for objects: Timsort, stable
- Java's Arrays.sort on int[]: unstable, but ints cannot show it
- C++ std::sort is unstable; std::stable_sort is stable
Sort by Multiple Keys
Stability is what lets you sort by multiple keys with ordinary one-key sorts. To list people by score and alphabetically within each score, sort by name first, then do a stable sort by score. The second pass groups by score, and inside each group it keeps the alphabetical order the first pass created.
The rule is: least important key first, most important key last, every pass stable. Reverse the order and the last pass wins: sorting by score and then by name gives a plain alphabetical list with the scores mixed up. Use an unstable sort in any pass and the earlier order is lost again.
This is how a spreadsheet or a web table behaves when you click one column header and then another: the newest click is the main key and the older clicks break ties, but only because the sort underneath is stable. In code you can also compare a tuple such as (score, name) in one pass, which gives the same result.
- Two passes: stable sort by the minor key, then by the major key
- One pass: compare (major, minor) as a tuple
- Radix sort is the same idea, applied digit by digit
Terms, operations, and practical uses
Key terms
- KeyThe part of a record the sort compares, such as a score.
- TieTwo records whose keys are equal.
- StableTied records leave the sort in the order they entered it.
- Tie-breakerA second value, such as the original index, compared when keys are equal.
Related lessons and problems
- Sorting AlgorithmsTime, space and stability for every sort.
- Insertion SortThe simplest stable sort, shift by shift.
- Selection SortThe long swap that makes it unstable.
- Radix SortMulti-key sorting with a stable pass per digit.
Code in Python, C++ and Java
def selection_sort(items, key):
a = list(items)
for i in range(len(a)):
m = i
for j in range(i + 1, len(a)):
if key(a[j]) < key(a[m]):
m = j
a[i], a[m] = a[m], a[i]
return a
def insertion_sort(items, key, move_equal=False):
a = list(items)
for i in range(1, len(a)):
item, j = a[i], i - 1
while j >= 0 and (key(a[j]) >= key(item) if move_equal else key(a[j]) > key(item)):
a[j + 1] = a[j]
j -= 1
a[j + 1] = item
return a
def show(records):
return " ".join(f"{name}{score}" for name, score in records)
people = [("Ana", 2), ("Ben", 3), ("Cal", 2), ("Dee", 1), ("Eve", 3), ("Fay", 1)]
by_score = lambda r: r[1]
print("selection sort: ", show(selection_sort(people, by_score)))
print("insertion sort: ", show(insertion_sort(people, by_score)))
print("insertion with >=:", show(insertion_sort(people, by_score, move_equal=True)))
print("built-in sort: ", show(sorted(people, key=by_score)))
shuffled = [("Eve", 3), ("Ana", 2), ("Fay", 1), ("Ben", 3), ("Dee", 1), ("Cal", 2)]
by_name = sorted(shuffled, key=lambda r: r[0])
print("name, then score: ", show(sorted(by_name, key=by_score)))
print("score, then name: ", show(sorted(sorted(shuffled, key=by_score), key=lambda r: r[0])))
tagged = [(r, i) for i, r in enumerate(people)]
fixed = selection_sort(tagged, key=lambda t: (t[0][1], t[1]))
print("selection + index:", show(r for r, _ in fixed))#include <algorithm>
#include <iostream>
#include <string>
#include <utility>
#include <vector>
using namespace std;
using Rec = pair<string, int>;
template <class T, class K>
vector<T> selectionSort(vector<T> a, K key) {
for (size_t i = 0; i < a.size(); i++) {
size_t m = i;
for (size_t j = i + 1; j < a.size(); j++)
if (key(a[j]) < key(a[m])) m = j;
swap(a[i], a[m]);
}
return a;
}
template <class K>
vector<Rec> insertionSort(vector<Rec> a, K key, bool moveEqual = false) {
for (size_t i = 1; i < a.size(); i++) {
Rec item = a[i];
int j = (int)i - 1;
while (j >= 0 && (moveEqual ? key(a[j]) >= key(item) : key(a[j]) > key(item))) {
a[j + 1] = a[j];
j--;
}
a[j + 1] = item;
}
return a;
}
string show(const vector<Rec>& rs) {
string s;
for (size_t i = 0; i < rs.size(); i++) s += (i ? " " : "") + rs[i].first + to_string(rs[i].second);
return s;
}
int main() {
vector<Rec> people = {{"Ana", 2}, {"Ben", 3}, {"Cal", 2}, {"Dee", 1}, {"Eve", 3}, {"Fay", 1}};
auto byScore = [](const Rec& r) { return r.second; };
auto cmpScore = [](const Rec& x, const Rec& y) { return x.second < y.second; };
auto cmpName = [](const Rec& x, const Rec& y) { return x.first < y.first; };
cout << "selection sort: " << show(selectionSort(people, byScore)) << "\n";
cout << "insertion sort: " << show(insertionSort(people, byScore)) << "\n";
cout << "insertion with >=: " << show(insertionSort(people, byScore, true)) << "\n";
vector<Rec> b = people;
stable_sort(b.begin(), b.end(), cmpScore);
cout << "built-in sort: " << show(b) << "\n";
vector<Rec> shuffled = {{"Eve", 3}, {"Ana", 2}, {"Fay", 1}, {"Ben", 3}, {"Dee", 1}, {"Cal", 2}};
vector<Rec> x = shuffled;
stable_sort(x.begin(), x.end(), cmpName);
stable_sort(x.begin(), x.end(), cmpScore);
cout << "name, then score: " << show(x) << "\n";
vector<Rec> y = shuffled;
stable_sort(y.begin(), y.end(), cmpScore);
stable_sort(y.begin(), y.end(), cmpName);
cout << "score, then name: " << show(y) << "\n";
vector<pair<Rec, int>> tagged;
for (size_t i = 0; i < people.size(); i++) tagged.push_back({people[i], (int)i});
auto fixed = selectionSort(tagged, [](const pair<Rec, int>& t) { return make_pair(t.first.second, t.second); });
vector<Rec> out;
for (auto& t : fixed) out.push_back(t.first);
cout << "selection + index: " << show(out) << "\n";
}import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
public class Main {
record Rec(String name, int score) {
public String toString() { return name + score; }
}
static <T> List<T> selectionSort(List<T> items, Comparator<T> cmp) {
List<T> a = new ArrayList<>(items);
for (int i = 0; i < a.size(); i++) {
int m = i;
for (int j = i + 1; j < a.size(); j++)
if (cmp.compare(a.get(j), a.get(m)) < 0) m = j;
T t = a.get(i); a.set(i, a.get(m)); a.set(m, t);
}
return a;
}
static List<Rec> insertionSort(List<Rec> items, boolean moveEqual) {
List<Rec> a = new ArrayList<>(items);
for (int i = 1; i < a.size(); i++) {
Rec item = a.get(i);
int j = i - 1;
while (j >= 0 && (moveEqual ? a.get(j).score() >= item.score() : a.get(j).score() > item.score())) {
a.set(j + 1, a.get(j));
j--;
}
a.set(j + 1, item);
}
return a;
}
static String show(List<Rec> rs) {
StringBuilder sb = new StringBuilder();
for (Rec r : rs) sb.append(sb.length() > 0 ? " " : "").append(r);
return sb.toString();
}
public static void main(String[] args) {
List<Rec> people = List.of(new Rec("Ana", 2), new Rec("Ben", 3), new Rec("Cal", 2),
new Rec("Dee", 1), new Rec("Eve", 3), new Rec("Fay", 1));
Comparator<Rec> byScore = Comparator.comparingInt(Rec::score);
Comparator<Rec> byName = Comparator.comparing(Rec::name);
System.out.println("selection sort: " + show(selectionSort(people, byScore)));
System.out.println("insertion sort: " + show(insertionSort(people, false)));
System.out.println("insertion with >=: " + show(insertionSort(people, true)));
List<Rec> b = new ArrayList<>(people);
b.sort(byScore);
System.out.println("built-in sort: " + show(b));
List<Rec> shuffled = List.of(new Rec("Eve", 3), new Rec("Ana", 2), new Rec("Fay", 1),
new Rec("Ben", 3), new Rec("Dee", 1), new Rec("Cal", 2));
List<Rec> x = new ArrayList<>(shuffled);
x.sort(byName);
x.sort(byScore);
System.out.println("name, then score: " + show(x));
List<Rec> y = new ArrayList<>(shuffled);
y.sort(byScore);
y.sort(byName);
System.out.println("score, then name: " + show(y));
List<int[]> tagged = new ArrayList<>();
for (int i = 0; i < people.size(); i++) tagged.add(new int[]{people.get(i).score(), i});
List<int[]> fixed = selectionSort(tagged, Comparator.<int[]>comparingInt(t -> t[0]).thenComparingInt(t -> t[1]));
List<Rec> out = new ArrayList<>();
for (int[] t : fixed) out.add(people.get(t[1]));
System.out.println("selection + index: " + show(out));
}
}Step through it
Running on Ana 2, Ben 3, Cal 2, Dee 1, Eve 3, Fay 1 (in name order)
Making Any Sort Stable
An unstable algorithm gives a stable result if no two keys are ever equal. Attach each record's original index and compare (key, index) instead of key alone. Ties are broken by the index, so the earlier record always wins. Selection sort run on (score, index) outputs Dee Fay Ana Cal Ben Eve, the stable order.
The cost is one extra number per record, O(n) memory, and a slightly slower comparison. That is often cheaper than switching algorithms, and it is the usual fix when a library only offers an unstable sort. It is also the trick behind decorate-sort-undecorate in older Python code.
- Key becomes (key, original index); every key is now unique
- Works with any comparison sort, including quick sort and heap sort
- Costs O(n) extra memory for the indexes
When Stability Does Not Matter
Skip the worry when the items are plain values, when every key is unique, or when the whole record is the key. In those cases stable and unstable sorts give the same output, and an unstable sort may be the faster or smaller choice: heap sort is O(n log n) worst case with O(1) extra memory, which no simple stable sort matches.
That trade-off is real. A stable sort that is fast in the worst case usually needs extra memory, like merge sort's O(n) buffer, while in-place stable merging is complex and slower. The in-place vs out-of-place sorting lesson covers the memory side.
- Plain numbers or unique keys: either kind gives the same output
- Records with ties shown to a user: choose a stable sort
- Tight memory and no ties that matter: an unstable in-place sort is fine
Practice and Next Steps
These problems sort records by a key where the order of ties is part of the answer, or where a second key breaks them.
- Sort Characters by Frequency: sort by count, then decide how ties appear
- Top K Frequent Words: two keys, count descending then word ascending
- Sort Colors: keys only, so stability cannot be seen
- Sorting Algorithms: every sort compared on time, space and stability