Timsort
The merge sort and insertion sort hybrid behind Python, Java and V8's built-in sorts: stable, O(n log n), and very fast on partly ordered data.
Description
Real data is rarely random. Logs arrive mostly in time order, lists get a few new items appended, spreadsheets are re-sorted by a column that's already partly sorted. Timsort, designed by Tim Peters for Python in 2002, is built to exploit that.
It scans the array for runs: stretches that are already ascending (or strictly descending, which it reverses). Short runs are extended to a minimum length, typically 32–64, with insertion sort, which is fast on small, nearly sorted pieces. Runs are then merged pairwise, like merge sort, following rules that keep merges balanced. A technique called galloping speeds up merges when one run's values mostly come before the other's.
The result is stable, O(n log n) in the worst case, and close to O(n) on data that's already mostly sorted. Timsort is the default sort in Python, for objects in Java and Android, and for Array.prototype.sort in V8 (Chrome and Node.js) since 2018. Rust's stable sort uses a related approach.
For everyday code, the practical lesson is: use the built-in sort. It's tuned, tested and almost always faster than anything hand-written. Know whether it's stable (in JavaScript it's guaranteed since ES2019), and pass a proper comparison function.
How it works
Timsort finds natural runs (here, three ascending runs) and merges them
- index 0: 3
- index 1: 8
- index 2: 12
- index 3: 15
- index 4: 2
- index 5: 6
- index 6: 9
- index 7: 1
- index 8: 4
- index 9: 7
- index 10: 11
- index 11: 14
Complexity
| Operation | Average | Worst |
|---|---|---|
| Random data | O(n log n) | O(n log n) |
| Already sorted or reversed | O(n) | O(n) |
| Partly ordered (few runs) | close to O(n) | O(n log n) |
Space: O(n) worst case for merging
JavaScript's sort compares values as strings unless you pass a comparison function: [10, 9, 1].sort() gives [1, 10, 9].
TypeScript implementation
How to use built-in sorts correctly in TypeScript: numeric comparison, stable multi-key sorting, and locale-aware strings.
// Using the built-in sort (Timsort in V8) correctly from TypeScript.
export function demo(): string[] {
const nums = [10, 9, 1, 100, 25];
const asStrings = [...nums].sort(); // default: compares as strings!
const numeric = [...nums].sort((a, b) => a - b);
// Stable multi-key sort: sort by the secondary key first, then the primary.
const people = [
{ name: "Sam", team: "Payments" }, { name: "Alex", team: "Checkout" },
{ name: "Priya", team: "Payments" }, { name: "Jordan", team: "Checkout" },
];
const byTeamThenName = [...people]
.sort((a, b) => a.name.localeCompare(b.name))
.sort((a, b) => a.team.localeCompare(b.team)); // stable: names stay sorted within each team
// Locale-aware comparison for user-facing text.
const words = ["Zebra", "ångström", "apple", "Äpple"];
const swedish = [...words].sort(new Intl.Collator("sv").compare);
return [
`default sort of numbers: [${asStrings.join(", ")}] (wrong)`,
`with (a, b) => a - b: [${numeric.join(", ")}]`,
`by team, then name: ${byTeamThenName.map((p) => `${p.team}/${p.name}`).join(", ")}`,
`Swedish collation: ${swedish.join(", ")}`,
];
}When to use it
Use it when
- Always, for general-purpose sorting in application code: use the language's built-in sort.
- When stability matters, for example sorting by one column and then another.
Avoid it when
- Keys are small integers and you need maximum speed: counting or radix sort.
- You only need the top k items: a heap or quickselect avoids sorting everything.
Pitfalls
- Forgetting the comparison function in JavaScript, which sorts numbers as strings.
- Inconsistent comparators (for example returning only true/false, or random values), which give unpredictable results.
- Sorting inside loops when one sort, or a heap, would do.
- Assuming stability in languages where the default sort isn't stable, such as C++'s
std::sort(usestd::stable_sort).
Alternatives
Merge sort
Choose it when you're implementing a stable sort yourself, for example for external sorting.
Radix sort
Choose it when you're sorting huge arrays of fixed-size integers.
Binary heap
Choose it when you need only the smallest or largest few items.