TimSort in Java
Learn how TimSort works: its time and space complexity, the algorithm in pseudo code, and a step-by-step visualisation that follows the Java code line by line.
Introduction
TimSort is a hybrid sort. It cuts the array into short runs, sorts each run with insertion sort, and then merges the runs together with merge sort until one sorted run is left.
Three ideas carry the whole algorithm:
- Run: a short block of the array, here at most 32 values long, that is sorted on its own before any merging starts.
- Insertion sort for small runs: on a few dozen values, insertion sort is faster than merge sort, because it has almost no overhead.
- Bottom-up merge: neighbouring runs are merged in pairs, so the sorted runs double in length on every pass, without any recursion.
Tim Peters designed TimSort in 2002 for Python’s built-in sort. Java has used it since Java 7 for Arrays.sort() on object arrays and for Collections.sort(), because it is stable and very fast on real-world data, which is often partly sorted already. The full algorithm finds the runs that already exist in the data, merges them according to a set of rules on a stack, and switches to a “galloping” mode when one run keeps winning.
This article uses a simplified TimSort with fixed-size runs: blocks of 32 values are sorted with insertion sort, and then merged bottom-up through one shared auxiliary array.
Performance Characteristics
Most of the work is in the merge passes, and their number depends only on how many runs there are, so this version takes about the same time for every input of a given size.
Time Complexity
Time complexity describes how the number of steps an algorithm takes grows as the input gets larger.
| Case | Time | When it happens |
|---|---|---|
| Best | $O(n \log n)$ | An already sorted array: insertion sort is fast, but every merge still copies |
| Average | $O(n \log n)$ | Random or mixed input |
| Worst | $O(n \log n)$ | Any input: the runs and merges have the same shape every time |
Why $n \log n$? Insertion sort on one run of 32 values costs at most a fixed amount, so sorting all the runs is $O(n)$. Each merge pass then copies every value once ($n$ work), and because the runs double in length on every pass, there are about $\log_2(n / 32)$ passes.
The full TimSort runs in $O(n)$ on an already sorted array, because it finds that the whole array is one natural run and has nothing to merge. This simplified version doesn’t look for natural runs, so it misses that speed-up. Adding a check that skips a merge when
a[mid]is not larger thana[mid + 1]gets most of it back.
Space Complexity
Space complexity describes how much extra memory an algorithm needs, beyond the input itself, as the input gets larger.
| Property | Value |
|---|---|
| Space | $O(n)$ for the auxiliary array. There is no recursion. |
| In place | No |
| Stable | Yes (insertion sort only moves a value past larger ones, and a merge takes the left value first on a tie) |
Algorithm (Pseudo Code)
TimSort starts by cutting the array into runs of 32 values; the last run may be shorter. Each run is sorted on its own with insertion sort: every value is taken out in turn and slid left past the larger values before it, until it reaches its place. After this first phase, the array is a row of short sorted runs.
Then the merging starts. In the first pass, the runs are merged in pairs: the first with the second, the third with the fourth, and so on. Each merge looks at the front value of both runs and keeps taking the smaller one, exactly as in merge sort. If a run is left without a partner at the end, it waits for the next pass. Every pass doubles the length of the sorted runs, until one run covers the whole array.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
sort(array):
for i = 0 to n - 1, in steps of SUB_ARRAY_SIZE:
insertionSort(array, i, min(i + SUB_ARRAY_SIZE, n))
aux = new array of length n
for sz = SUB_ARRAY_SIZE while sz < n, doubling sz each time:
for lo = 0 while lo < n - sz, in steps of 2 * sz:
merge(array, lo, lo + sz - 1, min(lo + 2 * sz - 1, n - 1))
merge(a, lo, mid, hi):
copy a[lo .. hi] into aux[lo .. hi]
i = lo, j = mid + 1
for k = lo to hi:
if j > hi: a[k] = aux[i++] // right run used up
else if i > mid: a[k] = aux[j++] // left run used up
else if aux[j] < aux[i]: a[k] = aux[j++]
else: a[k] = aux[i++]
After the pass for size sz, every block of 2 * sz values, starting at index 0, is sorted.
The loop condition
lo < n - szonly starts a merge when the right run has at least one value. A final run without a partner is not lost: it is already sorted, and a later pass, with a largersz, merges it in.
Visualization
The visualization below follows the Java code line by line, starting with the values 0 to 9 in shuffled order.
With SUB_ARRAY_SIZE = 32, ten values fit in one run, so the code would only run insertion sort and never merge. The visualization therefore starts with a run size of 4, so both phases are visible: three runs [0..3], [4..7] and [8..9], then two merge passes. Choose 32 in the footer to see what the real constant does with ten values.
Each step shows the array, the key or the auxiliary array, the pointers and the line of code that is running, with a short explanation of what just happened:
- Step through: use the arrows to move one step forward or back, or drag the slider to jump to any step.
- Play: press Play to run the steps automatically, and press it again to pause.
- Shuffle: press the shuffle button to start again with a new random order.
- Run size: choose the value of
SUB_ARRAY_SIZEin the footer: 2, 4 or 32. - Pointers in insertion sort: I is
i, the position the key was taken from, and J isj, the value the key is compared with. The bottom row shows the key under the dashed gap it may go into. - Pointers in merge: I is
i, the next value of the left run, and J isj, the next value of the right run, both inaux. K isk, the position in the array being written. The bottom row showsaux, and values that have already been copied back fade out. - Colours: the key and the value it is compared with are amber, a value being shifted or copied is salmon, and values in a sorted run are green.
- Runs: the gray bars mark where the runs begin.
Java Code
The implementation is a TimSort class with one public method, sort, and one private method, merge. sort runs both phases: it sorts each run with the range version of InsertionSort.sort, then drives the merge passes. merge combines two neighbouring sorted runs through the auxiliary array, which the class keeps in a field, aux. The run length is the constant SUB_ARRAY_SIZE = 32. One small helper, less, lives in a separate SortUtils class.
The complete code is in the algorithm-examples repository on GitHub:
TimSort.java, with the insertion sort inInsertionSort.javaand the helpers inSortUtils.java.
sort
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@Override
public <T extends Comparable<T>> T[] sort(T[] array) {
final int n = array.length;
InsertionSort insertionSort = new InsertionSort();
for (int i = 0; i < n; i += SUB_ARRAY_SIZE) {
insertionSort.sort(array, i, Math.min(i + SUB_ARRAY_SIZE, n));
}
aux = new Comparable[n];
for (int sz = SUB_ARRAY_SIZE; sz < n; sz = sz + sz) {
for (int lo = 0; lo < n - sz; lo += sz + sz) {
merge(array, lo, lo + sz - 1, Math.min(lo + sz + sz - 1, n - 1));
}
}
return array;
}
sort is the entry point, and it runs the two phases one after the other. The first loop steps through the array in blocks of SUB_ARRAY_SIZE and sorts each block with insertion sort. Math.min(i + SUB_ARRAY_SIZE, n) cuts the last block short when the length is not a multiple of 32.
The second phase is a bottom-up merge sort. The outer loop sets sz, the length of the sorted runs, starting at 32 and doubling on every pass. The inner loop walks over the array in steps of 2 * sz and merges each pair of runs: the left run is [lo .. lo + sz - 1] and the right run starts at lo + sz and is cut short at the end of the array.
Two details are worth noticing:
- The phases use different range styles.
insertionSort.sorttakes an exclusive end index, whilemergetakes inclusive indices formidandhi. That is why one call passesi + SUB_ARRAY_SIZEand the other subtracts 1. - An array of 32 values or fewer is one run, so the merge loop never runs, and the whole sort is a single insertion sort.
The class is called
TimSort, but it is the simplified version described in the introduction: it does not look for runs that already exist in the data, does not compute a minimum run length, does not keep a stack of runs, and does not gallop. It is really a bottom-up merge sort that uses insertion sort for blocks of 32. It sorts correctly and is stable, but it doesn’t have the speed of the JDK’s TimSort on partly sorted data.
InsertionSort.sort
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public <T extends Comparable<T>> T[] sort(T[] items, final int startIndex, final int endIndex) {
if (items == null || startIndex >= endIndex) {
return items;
}
for (int i = startIndex + 1; i < endIndex; i++) {
final T key = items[i];
int j = i - 1;
while (j >= startIndex && SortUtils.less(key, items[j])) {
items[j + 1] = items[j];
j--;
}
items[j + 1] = key;
}
return items;
}
This is the range version of the InsertionSort class, and it sorts only items[startIndex .. endIndex - 1]. Each value from startIndex + 1 onwards is taken out as the key, the larger values before it are shifted one position right, and the key drops into the gap they leave. The loop stops at startIndex, so it never reaches into the previous run.
The key only moves past values that are strictly larger than it, because less(key, items[j]) is false on a tie, so equal values stay in their original order, and this phase is stable. The Insertion Sort guide explains this method in detail.
merge
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
private <T extends Comparable<T>> void merge(T[] a, final int lo, final int mid, final int hi) {
int i = lo;
int j = mid + 1;
System.arraycopy(a, lo, aux, lo, hi + 1 - lo);
for (int k = lo; k <= hi; k++) {
if (j > hi) {
a[k] = (T) aux[i++];
} else if (i > mid) {
a[k] = (T) aux[j++];
} else if (less(aux[j], aux[i])) {
a[k] = (T) aux[j++];
} else {
a[k] = (T) aux[i++];
}
}
}
merge combines the sorted runs [lo .. mid] and [mid + 1 .. hi]. It copies the range into aux, at the same indices, so both runs are safe while a is overwritten. Then k walks from lo to hi, and each position gets the smaller of the two front values: aux[i] from the left run or aux[j] from the right run. The first two branches handle a run that is used up, and the right value is taken only when it is strictly less, so on a tie the left value goes first and the merge is stable.
aux is a raw Comparable[], because Java can’t create a generic T[] directly, so every value read from it needs the (T) cast. That is why the class carries @SuppressWarnings({"rawtypes", "unchecked"}).
auxis an instance field, not a local variable. Two threads that callsorton the sameTimSortobject at the same time share it and overwrite each other’s data, and the field keeps references to the last sorted values aftersortreturns. Creatingauxinsortand passing it tomergeavoids both problems.
less
1
2
3
public static <T extends Comparable<T>> boolean less(T firstElement, T secondElement) {
return firstElement.compareTo(secondElement) < 0;
}
This helper from SortUtils keeps both phases easy to read. less returns true when the first element is smaller than the second, using compareTo, so the algorithm works for any type that implements Comparable.
Running it
1
2
3
4
Integer[] numbers = {7, 2, 9, 4, 0, 8, 3, 6, 1, 5};
new TimSort().sort(numbers);
System.out.println(Arrays.toString(numbers));
// [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Create a TimSort, pass it an array, and the same array comes back sorted. With ten values and runs of 32, this example is sorted entirely by the insertion sort phase; the merges start once the array holds more than 32 values.
Summary
- TimSort is a hybrid sort: it sorts short runs with insertion sort, then merges the runs with merge sort.
- This implementation is simplified: fixed runs of 32 values, sorted with insertion sort, then merged bottom-up through one shared auxiliary array, with the run length doubling on every pass.
- After the pass for size
sz, every block of2 * szvalues is sorted, and the last pass sorts the whole array. - It runs in $O(n \log n)$ in the best, average and worst case, needs $O(n)$ extra space, and is stable but not in place.
- For production code, use the JDK:
Arrays.sort()on an object array andCollections.sort()run the full TimSort, which is $O(n)$ on sorted input. For primitive arrays, where stability doesn’t matter,Arrays.sort()uses a dual-pivot QuickSort.
