Sub topic 12
How Python, Java, C++, JavaScript, Rust and Go Sort
This chapter assumes you know what a stable sort is, how multi-key sorting depends on it, and the basic ideas behind Timsort, introsort and pattern-defeating quicksort (pdqsort) from the previous chapters. It also assumes you can read short programs in several languages.
Every standard library gives you a default sort. The question to ask is whether that default promises stability or only happens to be stable today. Code should rely only on documented guarantees, because the algorithm behind an implementation can change between versions.
The Guarantees at a Glance
| Language | Stable function | Unstable function | Typical algorithm |
|---|---|---|---|
| Python | `list.sort`, `sorted` | none | Timsort |
| Java | `List.sort`, `Collections.sort`, `Arrays.sort(Object[])` | `Arrays.sort(int[])` and other primitive arrays | Timsort for objects, dual-pivot quicksort for primitives |
| C++ | `std::stable_sort` | `std::sort` | Merge sort for stable, introsort-style hybrid for unstable |
| JavaScript | `Array.prototype.sort` (ES2019+) | none | Timsort in V8 |
| Rust | `sort`, `sort_by`, `sort_by_key` | `sort_unstable` and its variants | driftsort (stable), ipnsort, a pdqsort descendant (unstable), since Rust 1.81 |
| Go | `sort.SliceStable`, `sort.Stable`, `slices.SortStableFunc` | `sort.Slice`, `sort.Sort`, `slices.Sort` | pdqsort for unstable since Go 1.19 |
Python and JavaScript give you one stable sort and no unstable option. C++, Rust and Go make you choose. In C++ and Go, the short, obvious name is the unstable one.
Python and JavaScript: Stable by Default
Python has guaranteed stability for list.sort and sorted for many years. JavaScript only made Array.prototype.sort stable in the ES2019 specification. Older engines could reorder equal elements, so very old runtimes are the one case where JavaScript code still needs care.
const tasks = [
{ name: "a", p: 2 },
{ name: "b", p: 1 },
{ name: "c", p: 2 },
];
tasks.sort((x, y) => x.p - y.p);
console.log(tasks.map(t => t.name).join(" ")); // "b a c"Java: Objects Versus Primitives
Java chooses the algorithm based on what you sort. Sorting objects uses Timsort, which is stable. Primitive arrays use dual-pivot quicksort, which is unstable. With primitives that never matters, because two equal int values can't be told apart. A composite comparator lets you sort by several keys in one call:
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
public class Main {
record Person(String last, String first) {}
public static void main(String[] args) {
List<Person> people = new ArrayList<>(List.of(
new Person("smith", "carl"),
new Person("jones", "dana"),
new Person("smith", "anna"),
new Person("jones", "bob")));
people.sort(Comparator.comparing(Person::last)
.thenComparing(Person::first));
System.out.println(people);
}
}C++: Two Functions, Two Contracts
std::sort promises O(n log n) comparisons and nothing about equal elements. Implementations use introsort or a pdqsort-influenced variant of it. std::stable_sort promises stability. It runs in O(n log n) when it can allocate a buffer and falls back to O(n log² n) when it can't.
#include <algorithm>
#include <iostream>
#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}};
std::stable_sort(items.begin(), items.end(),
[](const Item& x, const Item& y) { return x.priority < y.priority; });
for (const auto& it : items) std::cout << it.name << ' ';
std::cout << '\n'; // prints: b d a c
}Rust: The Trade-off Is in the Name
In Rust, sort is stable and allocates a buffer. sort_unstable sorts in place without allocating. Because the API spells out the choice, nobody gets stability by accident.
fn main() {
let mut v = vec![("a", 2), ("b", 1), ("c", 2)];
v.sort_by_key(|&(_, k)| k); // stable
println!("{:?}", v); // [("b", 1), ("a", 2), ("c", 2)]
let mut nums = vec![5, 3, 9, 1];
nums.sort_unstable(); // no stability guarantee, no extra allocation
println!("{:?}", nums); // [1, 3, 5, 9]
}Go: The Common Trap
sort.Slice is the function most Go programmers reach for first, and it is not stable. Its pdqsort implementation can reorder equal elements. If input order matters, call sort.SliceStable, or slices.SortStableFunc in Go 1.21 and later.
package main
import (
"fmt"
"sort"
)
type Person struct {
Name string
Age int
}
func main() {
people := []Person{{"ann", 30}, {"bob", 25}, {"cat", 30}, {"dan", 25}}
sort.SliceStable(people, func(i, j int) bool { return people[i].Age < people[j].Age })
fmt.Println(people) // [{bob 25} {dan 25} {ann 30} {cat 30}]
}Choosing a Function
Exercise
A Go service sorts orders by customer ID with sort.Slice after they were already sorted by timestamp, and sometimes orders for the same customer come out of time order. What causes this, and what is the fix?
Show answer
sort.Slice is not guaranteed stable, so its pdqsort implementation can reorder orders that share a customer ID and lose the timestamp order. Replace it with sort.SliceStable, or slices.SortStableFunc. Another fix is a comparator that compares the timestamp when customer IDs are equal.
Exercise
Why is it harmless that Java's Arrays.sort(int[]) is unstable, when Arrays.sort on an array of objects must be stable?
Show answer
Two equal int values are indistinguishable, so no one can observe their relative order. Objects with equal keys can differ in other fields, so reordering them changes the visible result.