Vibe Engines
YouTube

Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path

Algorithms · Sorting

Sort What’s Already There.

Watch the explainer

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.

O(n log n) worst case, ~O(n) on nearly-sorted · stable · runs + insertion sort + merge
run

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, merge def timsort(a): minrun = compute_minrun(len(a)) # ~32-64 runs = [] i = 0 while i < len(a): run_end = find_run(a, i) # maximal sorted stretch if 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?

2. What is Timsort’s time complexity?

3. Why is Timsort described as stable?

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

runs found left to right (1 unit = 1 element) 5rev 7rev 462 merges, in the order the stack triggers them 5 + 7 = 124 + 6 = 1010 + 2 = 1212 + 12 = 24 time runs downward; each merge reads two adjacent runs and writes one
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.

StepWhereWhat happenedResultActionStack
1positions 0–4ascending run of 52, 5, 8, 11, 14push5
2positions 5–11descending run of 7, reversed3, 4, 6, 7, 9, 10, 12push5,7
3top of stackmerge 5 + 711 comparisonsmerge12
4positions 12–15descending run of 2, reversed; padded to 41, 13, 15, 16push12,4
5positions 16–21ascending run of 617, 18, 19, 20, 21, 22push12,4,6
6top of stackmerge 4 + 64 comparisonsmerge12,10
7positions 22–23ascending run of 2; end of array0, 23push12,10,2
8top of stackmerge 10 + 211 comparisonsmerge12,12
9top of stackmerge 12 + 1215 comparisonsmerge24

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

CaseTimeSpaceWhy
Timsort, already sorted or reversedO(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 sortedclose to O(n)O(n) worst10 adjacent swaps in a sorted 1,000-element list took 1907 comparisons. Few, long runs mean few, cheap merges.
Timsort, randomO(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 sortO(n log n) every timeO(n)Blind to order: 4,932 comparisons on 1,000 sorted numbers, 8,735 on random ones.
Insertion sortO(n²) worstO(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
  1. 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.
  2. Reverse only a strictly descending run. Reversing a run with equal elements would swap their order and destroy stability.
  3. 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.
  4. Then merge runs pairwise until one remains. That is ordinary merge sort, except the runs it merges were free.
  5. In the merge, take from the left half on ties. That single choice is what makes the whole sort stable.
  6. 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.
  7. Real CPython also keeps a run stack with balance invariants and galloping mode; this is the core idea without those refinements.
CPython · WebAssembly

Keep going

▶  Watch it explained

Timsort: Time and Space Complexity, From First Principles

Finished this one? 0 / 99 Algorithms done

Explore the topic

See this alongside everything else on the same subject — handbooks, system designs, challenges and tools, in one place.

More Algorithms