Algorithm Deep Dives

Tim Sort Explained

Updated June 8, 2026 7 min read

Tim Sort is arguably the most widely used sorting algorithm on the planet. Designed by Tim Peters in 2002 for Python, it now powers sorting in Python, Java (for objects), JavaScript's V8 engine, Swift, and Android. It is a hybrid of Merge Sort and Insertion Sort engineered specifically for the partially-ordered data we encounter in the real world.

The key insight: runs

Real data is rarely random — it usually contains runs, sequences that are already ascending or descending. Tim Sort scans the array for these natural runs, reverses descending ones, and treats them as pre-sorted building blocks. Short runs are extended to a minimum length using Insertion Sort.

How Tim Sort works

1) Identify runs and use Insertion Sort to bring each up to a minimum run length (typically 32-64). 2) Push runs onto a stack and merge them using a carefully tuned set of invariants that keep merges balanced. 3) Galloping mode accelerates merges when one run is consistently smaller, skipping ahead in big jumps.

Why it wins

Tim Sort is stable, achieves O(n) on already-sorted data, and guarantees O(n log n) worst case with O(n) space. It combines Insertion Sort's speed on small/ordered data with Merge Sort's reliability. Because real inputs are so often partially sorted, Tim Sort routinely beats pure Quick Sort or Merge Sort on practical workloads — which is why language designers chose it as the default.

Frequently asked questions

What languages use Tim Sort? +
Python (list.sort and sorted), Java (Arrays.sort for objects), JavaScript V8 (Array.prototype.sort since 2018), Swift, Kotlin, and Android all use Tim Sort or a close variant.
Why is Tim Sort the default in so many languages? +
Because it is optimized for real-world data that often contains partially sorted runs. It is stable, O(n) on sorted data, O(n log n) worst case, and faster than pure algorithms on practical inputs.
Is Tim Sort stable? +
Yes. Stability is one reason Java uses Tim Sort for object arrays, where preserving the order of equal elements matters for multi-key sorting.

See it in motion

Watch this algorithm and 9 others run step by step in our free interactive visualizer.

▶ Launch Visualiser

Related articles

← Back to all articles