Tim Sort
- Ω( n )
- Θ( n log n )
- O( n log n )
- space O( n )
This tim sort cuts the array into runs of 32 elements, sorts each run with insertion sort, and then merges neighbouring runs pairwise, doubling the run length each round. A merge is skipped when the two runs are already in order. It is stable, needs a buffer as long as the array, and gets close to linear time on sorted input.
- Comparisons count only element-against-element checks; loop and index checks are never counted.
- Reads and writes include reads and writes to helper buffers (merge, counting, radix, bucket and tim sort).
- A swap counts once, as a swap. It is never also counted as a read or a write.
- Real time is the average time of the counted sort on this device over repeated runs, measured once before playback and independent of animation speed. Visual time is the time spent animating, excluding pauses.
How tim sort works
With 5, 2, 6, 1, 4, 3 the whole array is shorter than one run of 32, so the sort consists of a single insertion sort over positions 0 to 5. A buffer of six slots is allocated afterwards, but the merge loop starts with a run length of 32, which is not smaller than 6, so it never executes. The table therefore shows writes made by insertion sort, and the buffer stays untouched. Each element is lifted out, larger neighbours shift one slot right, and the element is written into the gap.
The 2 is lifted, the 5 shifts right to give 5, 5, 6, 1, 4, 3 (the duplicated 5 is the gap not yet filled), and the 2 is written at index 0: 2, 5, 6, 1, 4, 3. The 6 is already in order. The 1 moves 6, 5 and 2 right in three writes, giving 2, 5, 6, 6, 4, 3 and 2, 5, 5, 6, 4, 3 and 2, 2, 5, 6, 4, 3, and its own write produces 1, 2, 5, 6, 4, 3. The 4 moves the 6 and the 5, then lands: 1, 2, 5, 6, 6, 3, then 1, 2, 5, 5, 6, 3, then 1, 2, 4, 5, 6, 3.
The last element, the 3, moves the 6, the 5 and the 4 and is written at index 2, ending at 1, 2, 3, 4, 5, 6 after 13 writes and 12 comparisons. To see the merging, imagine 70 elements instead. They form runs of 32, 32 and 6. In the first round the first two runs are compared at their boundary and merged only if the last element of the first run is larger than the first element of the second. The run of 6 has no partner yet, so it waits. In the second round the merged run of 64 meets the run of 6.
| Step | Change | Array after |
|---|---|---|
| 1 | Write 5 at index 1 | 5 5 6 1 4 3 |
| 2 | Write 2 at index 0 | 2 5 6 1 4 3 |
| 3 | Write 6 at index 3 | 2 5 6 6 4 3 |
| 4 | Write 5 at index 2 | 2 5 5 6 4 3 |
| 5 | Write 2 at index 1 | 2 2 5 6 4 3 |
| 6 | Write 1 at index 0 | 1 2 5 6 4 3 |
| 7 | Write 6 at index 4 | 1 2 5 6 6 3 |
| 8 | Write 5 at index 3 | 1 2 5 5 6 3 |
| 9 | Write 4 at index 2 | 1 2 4 5 6 3 |
| 10 | Write 6 at index 5 | 1 2 4 5 6 6 |
| 11 | Write 5 at index 4 | 1 2 4 5 5 6 |
| 12 | Write 4 at index 3 | 1 2 4 4 5 6 |
12 of 13 changes shown; the rest follow the same pattern until the array is sorted.
Pseudocode
RUN = 32
for start = 0, RUN, 2 * RUN, ... while start < n
insertion-sort a[start .. start + RUN - 1]
for width = RUN, 2 * RUN, ... while width < n
for lo = 0, 2 * width, ... while lo + width < n
mid = lo + width
hi = min(lo + 2 * width, n)
if a[mid] < a[mid - 1]
merge a[lo .. mid - 1] and a[mid .. hi - 1]
Why these complexities
Insertion sort on a run of at most 32 elements costs at most 32 times 31 divided by 2, or 496, comparisons, and there are n/32 runs, so the first phase is O(n) with a fairly large constant. Each merge round reads every element once into the buffer and writes it back in order, at a cost of at most n comparisons and n writes. The run length doubles each round, so there are about log₂ of n/32 rounds. That adds up to O(n log n) for the average and worst cases. On 1000 shuffled values it took 13,557 comparisons and about 13,570 writes to the array, plus 5,000 writes to the buffer.
The best case is linear because a merge is skipped when its boundary is already in order. On sorted input every insertion sort pass makes a single comparison per element, and one comparison per pair of neighbouring runs decides each skipped merge. 1000 sorted values cost 999 comparisons and no writes at all. The real tim sort goes further and also detects descending runs and reverses them, which this version does not do: 1000 reversed values cost 17,875 comparisons, a sizable penalty for a reversed array.
The buffer is allocated at the full length of the array whether or not a merge ever happens, which makes the space cost O(n). That is the price of a merge sort style algorithm, and it is the main reason to prefer a quick sort variant when memory is tight. Stability comes from two details: insertion sort shifts only strictly larger elements, and the merge takes from the left run on ties. Equal elements therefore never overtake each other.
Measured on this site
Exact counts from this site's own engine for 32 elements, using the same rules as the visualiser.
| Input | Comparisons | Writes | Swaps |
|---|---|---|---|
| Random | 338 | 341 | 0 |
| Already sorted | 31 | 0 | 0 |
| Reversed | 496 | 527 | 0 |
| Few distinct values | 200 | 191 | 0 |
When to use it
Use it, or the standard library sort built on it, whenever you need a stable sort for real-world data, which often contains ordered runs. It is the default in Python and for objects in Java.
Frequently asked questions
How does tim sort work?
It sorts short runs with insertion sort and merges the runs pairwise, skipping merges where two neighbouring runs are already in order.
How does this version differ from the real one?
It uses fixed runs of 32 elements and bottom-up merging. It has no run detection and no galloping.
Is tim sort stable?
Yes, and that is one reason it replaced quick sort in several standard libraries.
How much does tim sort cost on data that is already sorted?
In this version about n comparisons and no writes at all. Each run of 32 takes 31 comparisons in insertion sort, and one extra comparison per pair of neighbouring runs finds that the merge can be skipped. For 1000 sorted values that totals 999 comparisons, which is why the algorithm is a good fit for data that is mostly in order already.
Why does it copy so much data into the buffer?
The merge routine first copies the whole range being merged into the buffer, then writes the result back into the array. With 1000 shuffled values, five merge rounds ran, each copying about 1000 elements, which accounts for 5,000 buffer writes. The copy is what lets the merge write in place without overwriting values it has not read, and it is the reason the space cost is O(n).
Background
Tim Peters wrote tim sort in 2002 as the new list sort for CPython 2.3 and described it at length in a plain text file in the Python source tree. He designed it around a practical observation: real data is rarely random and tends to contain stretches that are already ordered, ascending or descending. The algorithm finds those runs instead of ignoring them. Java adopted it for object arrays in version 7, and V8 moved Array.prototype.sort to it in 2018, which made that sort stable.
The real algorithm differs from this version in several ways. It measures natural runs, extends short ones to a minimum length chosen from the array size, keeps a stack of pending runs under invariants that balance the merges, and uses galloping, an exponential search that skips over long stretches of one run during a merge. In 2015 a formal verification project found that the invariants in the Java and Python code did not always hold, which on huge inputs could make the Java version throw an exception; both were corrected. A 2018 analysis then proved the O(n log n) worst-case bound.
References
- Peters, listsort.txt, in the CPython source distribution, Objects/listsort.txt
- Auger, Juge, Nicaud, Pivoteau, On the Worst-Case Complexity of TimSort, ESA 2018
- Knuth, The Art of Computer Programming, vol. 3, section 5.2.4
Compare with
| Algorithm | Average time | Worst time |
|---|---|---|
| Intro Sort | Θ( n log n ) | O( n log n ) |
| Best time | Ω( n ) | good |
|---|---|---|
| Average time | Θ( n log n ) | good |
| Worst time | O( n log n ) | good |
| Worst space | O( n ) | fair |
Properties
- Stable
- Yes
- In place
- No
- Adaptive
- Yes
- Comparison-based
- Yes