Real-world data is rarely random — it comes in already-sorted stretches. Timsort, the default sort in Python and Java, is built to exploit exactly that. It scans for natural runs (maximal ascending or descending stretches, descending ones reversed), pads short runs up to a minimum length with a quick insertion sort, and then merges the runs together using a stack that keeps merges balanced (with a “galloping” fast-path when one run is consistently smaller). The payoff: already-sorted or nearly-sorted input sorts in close to O(n), while worst-case stays O(n log n) and the sort is stable. Watch the runs get found and merged.
A maximal already-sorted stretch (ascending, or descending then reversed).
minrun
A minimum run length (~32–64); short runs are extended with insertion sort.
merge
Combine two sorted runs into one, stably, like the merge step of merge sort.
galloping
A fast-path merge that binary-jumps when one run keeps winning.
timsort.js — find runs, then merge them
Ready
An array with some existing order. First we detect the natural runs — stretches already sorted. Then we merge adjacent runs into longer sorted ones until the whole array is sorted. Step to begin.
–
runs
0
merges
detect
phase
How it works
Timsort’s speed comes from not throwing away the order the data already has. A purely divide-and-conquer sort ignores that a chunk of the input might already be sorted; Timsort actively looks for those chunks. It walks the array once, identifying each maximal run — if a stretch is descending, it’s reversed in place (which keeps the sort stable). Runs shorter than minrun are grown to that length with binary insertion sort, which is very fast on tiny, nearly-sorted arrays. Then the runs are merged in a disciplined order: a stack of pending runs is kept, and merges are triggered to maintain size invariants so that no merge is wildly unbalanced. On data that arrives in a few long runs, there’s almost nothing to do — hence the near-linear best case — while random data still degrades gracefully to O(n log n).
1
Find natural runs
Scan left to right for maximal sorted stretches. Ascending runs are kept; a descending run is reversed in place so it becomes ascending — done stably.
2
Extend short runs (insertion sort)
If a run is shorter than minrun (~32–64), extend it to that length using binary insertion sort, which is fast on small, nearly-ordered pieces.
3
Merge runs on a stack
Push runs onto a stack and merge adjacent ones to keep their sizes balanced (roughly Fibonacci-like invariants), so merges are efficient. Galloping speeds up merges when one run consistently wins.
✓
Adaptive and stable
Nearly-sorted input has few, long runs → almost no work (~O(n)). Random input still merges in O(n log n). Equal elements keep their original order, so the sort is stable.
Worst case
O(n log n)
Nearly-sorted
~O(n)
Stable
Yes
Default in
Python, Java
The code
# Timsort, conceptually: detect runs, extend, mergedef timsort(a):
minrun = compute_minrun(len(a)) # ~32-64
runs = []
i = 0
while i < len(a):
run_end = find_run(a, i) # maximal sorted stretchif descending(a, i, run_end): reverse(a, i, run_end)
if run_end - i < minrun: # pad short runs
run_end = min(i + minrun, len(a))
binary_insertion_sort(a, i, run_end)
runs.append((i, run_end)); i = run_end
return merge_runs_with_stack(a, runs) # balanced, galloping merges
Quick check
1. What does Timsort look for to go fast on real data?
Timsort scans for runs: maximal already-sorted stretches (ascending, or descending which it reverses). Real data has many such runs, and exploiting them is what makes Timsort near-linear on nearly-sorted input.
2. What is Timsort’s time complexity?
Timsort is O(n log n) in the worst case like merge sort, but adaptive: when the data already contains long runs, there is little merging to do, so it approaches O(n).
3. Why is Timsort described as stable?
A stable sort preserves the relative order of equal elements. Timsort’s merge (favoring the left run on ties) and its careful run handling maintain that order, which is why it’s the default where stability matters, like Python’s sort.
FAQ
What is Timsort?
A hybrid, stable, adaptive sort (Tim Peters, 2002) combining merge sort and insertion sort. It finds natural sorted runs, extends short ones with insertion sort, and merges them with a balancing stack and galloping. O(n log n) worst case, ~O(n) on nearly-sorted input; the default sort in Python and Java.
Why is Timsort so fast on real-world data?
Real data often has long already-sorted stretches. Timsort detects these runs and only merges them, so a handful of long runs means very little work — approaching linear time. A sort that ignores existing order does the same work regardless of how sorted the input already is.
What is galloping mode?
When merging two runs, if one keeps winning, Timsort switches to galloping: it uses exponential/binary search to jump ahead and copy a whole block from the winning run at once, instead of element-by-element. It reverts to normal merging when the runs interleave evenly.
How does Timsort compare to quicksort?
Quicksort is usually faster on random primitive arrays and sorts in place, but is unstable with an O(n²) worst case. Timsort is stable, adaptive (much faster on partially-sorted data), and guaranteed O(n log n), using O(n) extra memory. Languages often use Timsort for object sorts and quicksort for primitives.
The picture: runs first, then merges
The 24 numbers traced below, with a toy minimum run length of 4. Highlighted boxes are runs that needed work: the descending run was reversed, and the short run was padded by insertion. The merges happen only between neighbouring runs, in stack order, so the sort never merges a huge run with a tiny one more often than needed.
Worked example, step by step
Sort [2, 5, 8, 11, 14, 12, 10, 9, 7, 6, 4, 3, 13, 1, 15, 16, 17, 18, 19, 20, 21, 22, 0, 23] with a toy minimum run length of 4 (real implementations use a value around 32–64, and sort short inputs by insertion alone, so a 24-element example would never reach the merge stage). Scan for runs, reverse descending ones, pad short ones by insertion, push each run on a stack, and merge whenever the top runs break the size rule: each run must be longer than the two above it combined, and longer than the one above it. The stack column lists run lengths from bottom to top.
Step
Where
What happened
Result
Action
Stack
1
positions 0–4
ascending run of 5
2, 5, 8, 11, 14
push
5
2
positions 5–11
descending run of 7, reversed
3, 4, 6, 7, 9, 10, 12
push
5,7
3
top of stack
merge 5 + 7
11 comparisons
merge
12
4
positions 12–15
descending run of 2, reversed; padded to 4
1, 13, 15, 16
push
12,4
5
positions 16–21
ascending run of 6
17, 18, 19, 20, 21, 22
push
12,4,6
6
top of stack
merge 4 + 6
4 comparisons
merge
12,10
7
positions 22–23
ascending run of 2; end of array
0, 23
push
12,10,2
8
top of stack
merge 10 + 2
11 comparisons
merge
12,12
9
top of stack
merge 12 + 12
15 comparisons
merge
24
The sorted answer needed 67 comparisons in total. A plain top-down merge sort on the same 24 numbers used 64. That is slightly more, not fewer, and it is worth being honest about why: this input is built from short runs, so scanning, padding and merging all cost comparisons and there is little order to exploit. The advantage appears when runs are long, as the complexity table below shows with 1,000 elements. Two details are easy to miss. The descending run was reversed before being pushed, so every stack entry is ascending. And the last run, 0 and 23, is shorter than the minimum only because the array ended; nothing was left to pad it with.
Complexity and trade-offs
Case
Time
Space
Why
Timsort, already sorted or reversed
O(n)
O(1)
One run covers everything, so there is nothing to merge. Counted for 1,000 distinct numbers: 999 comparisons sorted and 999 reversed.
Timsort, nearly sorted
close to O(n)
O(n) worst
10 adjacent swaps in a sorted 1,000-element list took 1907 comparisons. Few, long runs mean few, cheap merges.
Timsort, random
O(n log n)
O(n)
8643 comparisons for 1,000 random numbers. Merging copies a run into a buffer, so temporary memory can grow with n.
Top-down merge sort
O(n log n) every time
O(n)
Blind to order: 4,932 comparisons on 1,000 sorted numbers, 8,735 on random ones.
Insertion sort
O(n²) worst
O(1)
Ideal on sorted input (999 comparisons) but 255,888 on the random 1,000. This is why Timsort uses it only for tiny pieces.
Counts above are comparisons made by Python’s built-in sort, measured by wrapping each item in a class that counts calls to <. Timsort’s goal is to be never much worse than merge sort and far better when data has structure. The cost is complexity: run detection, a stack rule and a merge buffer make it far more code than a plain merge sort. It is also a comparison sort, so it cannot beat n log n on truly random data, and it is stable, which is why standard libraries can use it for sorting records by one field at a time.
Common mistakes
Taking the right element on a tie when merging
Stability depends on one character. Merging [(1,'a')] with [(1,'b')] must give a then b. With R <= L instead of R < L the output is [(1,'b'), (1,'a')]: equal keys swapped.
Reversing a run that is not strictly descending
Only strictly descending runs may be reversed in place. If equal elements count as descending, [(5,'a'), (5,'b'), (5,'c'), (4,'d')] is reversed to [(4,'d'), (5,'c'), (5,'b'), (5,'a')]: sorted, but c, b, a are now backwards. The strict test keeps a, b, c as an ascending run of equals.
Merging runs into one growing accumulator
Merging each new run into everything so far looks simpler than a stack, but it recopies the big run every time. For 64 runs of 16 elements it copies 33,264 elements; merging neighbours of similar size copies 6,144. The stack rule exists to keep merged runs similar in size.
Calling JavaScript’s sort on numbers without a comparator
[10, 9, 1, 100, 25].sort() returns [1, 10, 100, 25, 9] because the default comparison converts items to strings. Pass (a, b) => a - b for numbers, which gives [1, 9, 10, 25, 100].
Sorting by two keys in the wrong order
Because the sort is stable, sort by the secondary key first, then the primary. Records [('b',2),('a',1),('c',2),('d',1),('e',2)] sorted by letter, then by number, give ('a',1), ('d',1), ('b',2), ('c',2), ('e',2). Doing it in the opposite order loses the letter ordering inside each group.
Where this shows up
Sorting records by several columns
A stable sort lets you apply one pass per column, least significant first, with no custom multi-key comparator. Table UIs commonly rely on this so that clicking a second column header keeps the first column’s order among ties.
Appending to an already sorted list
Add 100 new values to the end of a sorted list of 10,000 and sort again: 11,908 comparisons here, against 119,983 for 10,000 random values. The long sorted prefix is one run, so only the tail costs real work.
Logs and time series
Timestamps mostly arrive in order, with small local disorder from buffering and retries. That is the shape run detection is built for, so re-sorting a day of events costs close to a single pass.
Merging sorted shards
Combining the sorted outputs of several workers is exactly a merge of runs. Concatenating them and calling the library sort lets run detection find each shard, so it does the merge for you.
SOLVE IT YOURSELF
Solve it: sort the way Python actually sorts
Real data is not random — it arrives in already-ordered stretches. Timsort finds those natural runs instead of ignoring them, so nearly-sorted input costs O(n) rather than O(n log n). It is the sort behind list.sort() and Array.prototype.sort. Python or TypeScript.
YOUR TASK
Implement timsort(arr, key=None): return a new sorted list, leave the input alone, and keep equal elements in their original order (stability). Set the module-level run counter so the tests can see how many natural runs you found.
HINTS — 7 IDEAS
Scan for a natural run at each position: how far does the data already ascend? If it descends instead, take that stretch and reverse it — descending runs are just as useful as ascending ones.
Reverse only a strictly descending run. Reversing a run with equal elements would swap their order and destroy stability.
Short runs are wasteful, so pad each one up to MIN_RUN (32 here) with binary insertion sort — cheap at that size, and it keeps the run sorted.
Then merge runs pairwise until one remains. That is ordinary merge sort, except the runs it merges were free.
In the merge, take from the left half on ties. That single choice is what makes the whole sort stable.
Already-sorted input yields exactly one run — the scan reaches the end and there is nothing left to merge. That is the O(n) best case.
Real CPython also keeps a run stack with balance invariants and galloping mode; this is the core idea without those refinements.