Interactive demo

Timsort Visualization

Timsort, written by Tim Peters for Python in 2002, is a merge sort that looks for runs: parts of the array that are already in order. Real data often contains such runs, and timsort uses them instead of sorting from scratch.

Your browser does not support the HTML5 canvas tag.

Choose “Sorted”, “Reversed” or “Nearly sorted”: timsort needs only a few steps. The dashed lines separate the runs on the stack.

Playback

Comparisons
0
Writes
0

Array

Legend

  • Not in a run yet
  • In a run
  • Inserted or copied element
  • Compared heads
  • Final position

Runtime and properties

Best case

O(n)

Sorted or reversed input is a single run: n − 1 comparisons and done.

Average case

O(n log n)

Short runs are extended to a minimum length, then merged in a balanced way.

Worst case

O(n log n)

The rules for merging keep the run lengths balanced, like merge sort.

Extra memory

O(n)

Merging copies the shorter of two runs, at most n / 2 elements.

Stable

Yes

Runs are only reversed if they are strictly descending, and ties keep the left element first.

In-place

No

The shorter run is copied to a temporary array.

n is the number of elements. O(n log n) is the best a sorting algorithm based on comparisons can achieve.

Compared with the other sorting algorithms

AlgorithmBest caseAverage caseWorst caseExtra memoryStableIn-place
Bubble sortO(n)O(n²)O(n²)O(1)YesYes
Selection sortO(n²)O(n²)O(n²)O(1)NoYes
Insertion sortO(n)O(n²)O(n²)O(1)YesYes
Shell sortO(n log n)≈ O(n1.25)O(n1.5)O(1)NoYes
Tree sortO(n log n)O(n log n)O(n²)O(n)YesNo
Tournament sortO(n log n)O(n log n)O(n log n)O(n)YesNo
HeapsortO(n log n)O(n log n)O(n log n)O(1)NoYes
SmoothsortO(n)O(n log n)O(n log n)O(1)NoYes
Merge sortO(n log n)O(n log n)O(n log n)O(n)YesNo
Patience sortO(n)O(n log n)O(n log n)O(n)YesNo
Timsort this pageO(n)O(n log n)O(n log n)O(n)YesNo
Block sortO(n)O(n log n)O(n log n)O(1)YesYes
QuicksortO(n log n)O(n log n)O(n²)O(log n)NoYes
IntrosortO(n log n)O(n log n)O(n log n)O(log n)NoYes
FluxsortO(n)O(n log n)O(n log n)O(n)YesNo
CrumsortO(n)O(n log n)O(n log n)O(log n)NoYes

1. Find runs

Timsort walks through the array and finds the next run. A strictly descending run is simply reversed. A run shorter than the minimum run length is extended with binary insertion sort.

2. Keep the stack balanced

Every run goes onto a stack. Whenever the run lengths on the stack become unbalanced, neighboring runs are merged, so the merges stay about as balanced as in merge sort.

3. Simplified here

This visualization uses a minimum run length of 4 (the original uses 32 to 64 and sorts arrays below 64 elements with binary insertion sort alone) and merges element by element. The original also switches to “galloping” when one run keeps winning, and current Python merges runs with the newer powersort strategy.

Credits