/utils

Timsort

Find the runs that real data already contains, extend short ones with insertion sort, and merge runs on a stack. Stable, O(n) on sorted input, O(n log n) always.

SolvesSorting

best
O(n)
average
O(n log n)
worst
O(n log n)
space
O(n)

Real data is rarely random. It often contains stretches that are already sorted. Timsort looks for these runs first. It then merges them like merge sort, but only where needed.

Already sorted: the whole array is one natural run. Timsort finds it with n − 1 comparisons and never merges: O(n). A strictly descending array is also one run and gets reversed.

10213243546576879810911101211

run stack (lengths) = []

1MIN_RUN = 42 3 4def insertion_sort(a, lo, start, hi):5    for i in range(start, hi):6        key = a[i]7        j = i - 18        while j >= lo and a[j] > key:9            a[j + 1] = a[j]10            j = j - 111        a[j + 1] = key12 13 14def find_run(a, lo, n):15    hi = lo + 116    if hi == n:17        return hi18    descending = a[hi] < a[lo]19    hi = hi + 120    if descending:21        # strictly descending: reverse it22        while hi < n and a[hi] < a[hi - 1]:23            hi = hi + 124        i = lo25        j = hi - 126        while i < j:27            a[i], a[j] = a[j], a[i]28            i = i + 129            j = j - 130    else:31        while hi < n and a[hi] >= a[hi - 1]:32            hi = hi + 133    return hi34 35 36def merge(a, lo, mid, hi):37    left = a[lo:mid]38    i = 039    j = mid40    k = lo41    while i < len(left) and j < hi:42        if left[i] <= a[j]:43            a[k] = left[i]44            i = i + 145        else:46            a[k] = a[j]47            j = j + 148        k = k + 149    while i < len(left):50        a[k] = left[i]51        i = i + 152        k = k + 153 54 55def merge_at(a, sizes, k):56    lo = sum(sizes[:k])57    mid = lo + sizes[k]58    hi = mid + sizes[k + 1]59    merge(a, lo, mid, hi)60    sizes[k] = sizes[k] + sizes[k + 1]61    sizes.pop(k + 1)62 63 64def collapse(a, sizes):65    while len(sizes) > 1:66        k = len(sizes) - 267        b = sizes[k]68        c = sizes[k + 1]69        if k > 0 and sizes[k - 1] <= b + c:70            if sizes[k - 1] < c:71                k = k - 172            merge_at(a, sizes, k)73        elif b <= c:74            merge_at(a, sizes, k)75        else:76            break77 78 79def timsort(a):80    n = len(a)81    sizes = []82    lo = 083    while lo < n:84        run_end = find_run(a, lo, n)85        hi = run_end86        if run_end - lo < MIN_RUN:87            hi = min(lo + MIN_RUN, n)88            insertion_sort(a, lo, run_end, hi)89        sizes.append(hi - lo)90        collapse(a, sizes)91        lo = hi92    while len(sizes) > 1:93        merge_at(a, sizes, len(sizes) - 2)94    return a
1 / 3

Run of 12 at index 0.

comparisons
11
merges
0

How it works

Tim Peters wrote Timsort for Python in 2002 [1]. Java (for objects) and Android use it.

  1. Find a run. Take the longest ascending stretch at the current position. A strictly descending stretch is reversed, which is safe because it has no equal keys.
  2. Extend short runs. A run shorter than MIN_RUN is filled up to that length with insertion sort. The demo uses 4. CPython picks a value between 32 and 64.
  3. Push the run onto a stack of runs.
  4. Merge by the policy. The two implementations differ only in this step. Both merge neighbouring runs only.
  5. At the end, merge all runs left on the stack.

The merge copies the left run to a buffer and takes the smaller front value each time. It is stable, like the merge in merge sort.

Classic rules

Look at the top three runs A, B, C (C on top). Merge while A≤B+CA \le B + C or B≤CB \le C. When these rules hold on the whole stack, the run lengths grow at least like the Fibonacci numbers from top to bottom. So the stack holds O(log⁡n)O(\log n) runs.

Powersort

Munro and Wild published Powersort in 2018 [2]. CPython 3.11 replaced the classic rules with it.

  1. Map the array to the interval [0,1)[0, 1). Each run becomes a segment.
  2. The power of the boundary between two runs is the depth at which a perfect binary tree over [0,1)[0, 1) separates the midpoints of the two runs.
  3. Before pushing a run, merge the top two runs while the boundary between them has a larger power than the new boundary.

The merges then follow a nearly balanced tree over the runs. The total merge cost is within O(n)O(n) of the best possible order.

This page simplifies three things. Real Timsort uses binary insertion sort, a galloping mode inside merges, and the classic version checks four runs instead of three.

Complexity

CaseInputTime
Bestsorted or reverse sortedO(n)O(n)
AveragerandomO(nlog⁡n)O(n \log n)
Worstno long runsO(nlog⁡n)O(n \log n)

A sorted array is one run: n−1n - 1 comparisons and no merge. Both policies keep the merges balanced. The total merge cost is O(nlog⁡n)O(n \log n), and O(n+nlog⁡r)O(n + n \log r) for rr runs. The merge buffer needs up to n/2n/2 values.

Implementations

  • Classic rules: the original policy. It checks run lengths only and is easy to state. Its merge order is sometimes far from the best one.
  • Powersort: computes one power per boundary. It needs a few more lines, but its merge cost is near-optimal and its correctness proof is short.

Pitfalls

  • Only a strictly descending run may be reversed. With equal keys the reversal would change their order and the sort would lose stability.
  • The merge rules matter. Merging a long run with a short one again and again costs O(n2)O(n^2).
  • The classic rules on the top three runs are not enough to keep the stack short. In 2015 this bug was found in both Java and CPython [3]. Real implementations check four runs.

Related

References

  1. T. Peters, “Timsort: description of the algorithm (listsort.txt),” CPython source, Objects/listsort.txt, 2002.
  2. J. I. Munro and S. Wild, “Nearly-Optimal Mergesorts: Fast, Practical Sorting Methods That Optimally Adapt to Existing Runs,” in 26th Annual European Symposium on Algorithms (ESA 2018), 2018, pp. 63:1–63:16.
  3. S. de Gouw et al., “OpenJDK's Java.utils.Collection.sort() Is Broken: The Good, the Bad and the Worst Case,” in Computer Aided Verification (CAV 2015), 2015, pp. 273–289.

Further reading

  • K. Mehlhorn and P. Sanders, Algorithms and Data Structures: The Basic Toolbox, Springer, 2008.

Full bibliography