Sub topic 12
How Python, Java, C++, JavaScript, Rust and Go Sort
This chapter assumes you know what a stable sort is, how to sort by several keys, and how to break ties with the original index. Earlier chapters covered those topics. It also assumes you have a rough idea of how Timsort, introsort and pattern-defeating quicksort (pdqsort) work. Here we look at the actual functions in six languages: which ones promise stability, which algorithm usually sits behind each one, and what common mistakes catch people out.
Keep one rule in mind throughout. A library's guarantee is what the documentation or language specification promises. Its implementation is what the current version happens to do. Write code that depends only on the guarantee. An unstable sort may return equal elements in input order on small inputs today and stop doing so after an upgrade.
The Summary Table
| Language | Stable function | Unstable function | Typical algorithm behind it |
|---|---|---|---|
| Python | `list.sort`, `sorted` | none | Timsort (Powersort merge policy since 3.11) |
| 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::list::sort` | `std::sort`, `std::partial_sort` | Merge sort for stable; introsort for `std::sort` |
| JavaScript | `Array.prototype.sort`, `toSorted` (ES2019+) | none | Timsort in V8 |
| Rust | `sort`, `sort_by`, `sort_by_key`, `sort_by_cached_key` | `sort_unstable`, `sort_unstable_by`, `sort_unstable_by_key` | driftsort for stable; ipnsort (pdqsort-derived) for unstable |
| Go | `sort.Stable`, `sort.SliceStable`, `slices.SortStableFunc` | `sort.Sort`, `sort.Slice`, `slices.Sort`, `slices.SortFunc` | Insertion sort blocks plus in-place merging for stable; pdqsort for unstable |
The languages fall into two groups. Python and JavaScript offer one sort, and it is stable. Java, C++, Rust and Go offer both kinds and expect you to pick one. When you pick wrong, the code still compiles, so the bug only shows up as an occasional wrong order among equal elements.
Python
Python has one sorting algorithm, and the language guarantees it is stable. list.sort() sorts in place and returns None. sorted() takes any iterable and returns a new list. Both take a key function and a reverse flag.
records = [("alice", 3), ("bob", 1), ("carol", 3), ("dave", 2)]
by_score = sorted(records, key=lambda r: r[1])
print(by_score)
# [('bob', 1), ('dave', 2), ('alice', 3), ('carol', 3)]
desc = sorted(records, key=lambda r: r[1], reverse=True)
print(desc)
# [('alice', 3), ('carol', 3), ('dave', 2), ('bob', 1)]Look at the second result. reverse=True does not reverse the stable output. It sorts in descending order and still keeps alice ahead of carol. If you sorted ascending and then called .reverse() on the result, carol would come before alice. Use the flag when you want to keep stability.
Python 3 dropped the cmp argument. If you already have a two-argument comparison function, wrap it with functools.cmp_to_key. A key function is usually faster, because Python computes each key once and compares the keys directly.
Java
Java decides stability by element type. That trips people up, because both calls are spelled Arrays.sort.
Arrays.sort(int[]),Arrays.sort(double[])and the other primitive overloads use dual-pivot quicksort. They are not stable. That does no harm, because two equalints cannot be told apart.Arrays.sort(Object[]),Arrays.sort(T[], Comparator),Collections.sortandList.sortare documented as stable. The JDK implements them with Timsort.Arrays.parallelSorton object arrays is also stable.
Combine keys with Comparator.comparing and thenComparing. That gives a correct multi-key order in a single pass:
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);
}
}The JDK's Timsort detects some comparators that break the contract and throws IllegalArgumentException: Comparison method violates its general contract!. The classic cause is a comparator written as (a, b) -> a.x - b.x, which overflows for large or negative values. Use Integer.compare(a.x, b.x) or Comparator.comparingInt instead.
C++
std::sort makes no stability promise. Since C++11 the standard requires O(n log n) comparisons in the worst case. libstdc++ and libc++ meet that with introsort-style algorithms. std::stable_sort is stable. It is a merge sort that tries to allocate a temporary buffer. If the allocation fails, it falls back to an in-place merge that costs O(n log² n) comparisons. std::list::sort is also stable. std::partial_sort and std::nth_element are not stable.
#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
}C++20 adds std::ranges::sort and std::ranges::stable_sort. They accept a projection, which plays the role of a key function: std::ranges::stable_sort(items, {}, &Item::priority). Stability works the same way as in the older functions.
The comparator must define a strict weak ordering, and it must return true only for "less than". If you pass <=, the program has undefined behavior. In practice that can mean reading past the end of the array, not just getting a wrong order.
JavaScript
Before ES2019, engines could choose freely. Older V8 versions used an unstable quicksort for arrays longer than 10 elements, so stability depended on array length. ES2019 made Array.prototype.sort stable everywhere, and V8 switched to Timsort. The non-mutating toSorted (ES2023) follows the same rules.
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"
console.log([10, 9, 1].sort()); // [1, 10, 9]
console.log([10, 9, 1].sort((a, b) => a - b)); // [1, 9, 10]The second example shows the most common JavaScript mistake. With no comparator, sort converts elements to strings and compares them as UTF-16 code units. The other common mistake is a comparator that returns a boolean, such as (a, b) => a > b. It never returns a negative number, so the engine cannot tell "less" from "equal". The result depends on the engine and is often wrong. Return a negative number, zero, or a positive number.
Rust
Rust names stability in the method name. sort, sort_by and sort_by_key are stable and allocate a buffer. Since Rust 1.81 the stable sort is driftsort, a merge-based successor to the earlier Timsort-like code. The sort_unstable* family sorts in place without allocating, and it is usually faster. Since 1.81 it uses ipnsort, which descends from pdqsort.
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]
let mut fs = vec![2.5_f64, -1.0, 0.0];
fs.sort_by(|a, b| a.total_cmp(b)); // f64 is not Ord
println!("{:?}", fs); // [-1.0, 0.0, 2.5]
}sort_by_cached_key calls the key function once per element. It is useful when the key is expensive, such as a string you build or a value you parse. It is also stable. Internally it builds (key, original_index) pairs and sorts them with the unstable sort, which is the index-tiebreak trick from an earlier chapter.
Floats do not implement Ord, because NaN cannot be ordered. That is why v.sort() on a Vec<f64> does not compile. Use total_cmp. Since 1.81, a comparator that is not a total order may cause the sort to panic. It will not cause memory unsafety.
Go
Go's older sort package and the newer generic slices package (Go 1.21) both offer two kinds of sort.
- Unstable:
sort.Sort,sort.Slice,slices.Sort,slices.SortFunc. Since Go 1.19 these use pdqsort. - Stable:
sort.Stable,sort.SliceStable,slices.SortStableFunc. These run insertion sort on small blocks and then merge the blocks in place. They need no extra memory, but they do more work: O(n log n) comparisons and up to O(n log² n) swaps.
package main
import (
"cmp"
"fmt"
"slices"
"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}]
more := []Person{{"eve", 40}, {"fay", 20}, {"gus", 40}}
slices.SortStableFunc(more, func(a, b Person) int { return cmp.Compare(a.Age, b.Age) })
fmt.Println(more) // [{fay 20} {eve 40} {gus 40}]
}The two packages use different comparator shapes. sort.Slice takes a "less" function over indices. slices.SortFunc takes a three-way function over values that returns a negative number, zero, or a positive number. cmp.Compare returns that kind of value for ordered types, and it puts NaN before every other float.
Patterns Across the Six Languages
- Languages that offer both kinds make the short name unstable in C++ and Go (
std::sort,sort.Slice) and the short name stable in Rust (sort). Java chooses by element type. - Stable sorts are almost always merge-based and usually allocate up to n/2 or n extra elements. Go's stable sort is the exception: it uses no extra memory and pays with more swaps.
- Unstable sorts are quicksort hybrids (introsort, pdqsort, ipnsort, dual-pivot quicksort) that sort in place.
- Every library assumes your comparator is consistent. What happens when it is not varies: Java throws an exception, Rust may panic, C++ has undefined behavior, and JavaScript gives an engine-dependent order.
Exercise
A Java service sorts a List<Order> by status and expects orders with the same status to stay in arrival order. A teammate proposes converting the list to an int[] of order IDs and calling Arrays.sort for speed. What changes?
Show answer
The original List.sort is guaranteed stable, so orders with equal status keep their arrival order. Arrays.sort(int[]) sorts the IDs themselves with dual-pivot quicksort. That sort is unstable, but more importantly it sorts by ID, not by status, so the result no longer means the same thing. Keep the object sort, or sort an Order[] with a comparator. Both object sorts are stable.
Exercise
In JavaScript, why does [3, 20, 100].sort() return [100, 20, 3], and what does arr.sort((a, b) => a > b) do wrong?
Show answer
Without a comparator, elements are compared as strings, and "100" < "20" < "3". The boolean comparator returns true or false, which become 1 or 0. It never returns a negative number, so the engine cannot tell "less" from "equal", and the result depends on the engine. Use (a, b) => a - b.
Exercise
In Rust you need to sort 10 million log entries by a key that takes a costly string parse, and equal keys must keep input order. Which method fits, and why?
Show answer
Use sort_by_cached_key. It parses each key once instead of O(n log n) times, and it is stable, because it sorts (key, index) pairs. sort_by_key is also stable, but it would call the parse on every comparison.