Post

Introsort in Java

Learn how Introsort 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.

Introsort in Java

Introduction

Introsort, short for introspective sort, is a hybrid sort. It starts as QuickSort, keeps an eye on how deep the recursion goes, and switches to heap sort when QuickSort is running into its worst case. Small ranges are finished with insertion sort.

Three ideas carry the whole algorithm:

  • QuickSort by default: each range is partitioned around a pivot, which is the fastest approach on typical data.
  • Depth limit: a budget of about $2 \log_2 n$ partition levels. When a range uses it up, the pivots have been bad too often, and the range is sorted with heap sort, which is always $O(n \log n)$.
  • Insertion sort for small ranges: below a size threshold, insertion sort is faster than partitioning, because it has almost no overhead.

David Musser described Introsort in 1997, to get QuickSort’s speed without its $O(n^2)$ worst case. It is the algorithm behind std::sort in the main C++ standard libraries, and .NET’s Array.Sort uses it too. Java’s own Dual-Pivot QuickSort, since JDK 14, uses the same idea and falls back to heap sort when its recursion gets too deep.

This article uses Introsort with a random Lomuto pivot and a loop on the left part: a random pivot is swapped to the end of the range, the right part is sorted recursively, and a while loop carries on with the left part.

Performance Characteristics

Introsort is designed to run as fast as QuickSort on average while keeping heap sort’s $O(n \log n)$ guarantee, and the depth limit decides which of the two does the work.

Time Complexity

Time complexity describes how the number of steps an algorithm takes grows as the input gets larger.

CaseTimeWhen it happens
Best$O(n \log n)$The pivots split the ranges evenly
Average$O(n \log n)$Random or mixed input
Worst$O(n \log n)$By design: bad pivots use up the depth limit, and heap sort takes over (see below)

Why $n \log n$? While the pivots are good, it is QuickSort: each level of partitioning touches every value once, and there are about $\log_2 n$ levels. When the pivots are bad, the recursion can’t go deeper than the depth limit of $2 \log_2 n$ levels, and the remaining ranges are heap sorted in $O(n \log n)$. The insertion sorts only ever see ranges of at most 17 values, so they add $O(n)$ in total.

The Java code below doesn’t quite keep this guarantee. Its while loop doesn’t reduce depth for the left part, and its partition sends every value equal to the pivot to the left. An array of equal values therefore runs in $O(n^2)$ and never reaches heap sort. The warning in the introspectiveSort section explains it and shows the fix.

Space Complexity

Space complexity describes how much extra memory an algorithm needs, beyond the input itself, as the input gets larger.

PropertyValue
Space$O(\log n)$ for the recursion stack, because only the right part is sorted with recursion
In placeYes
StableNo (partitioning and heap sort swap values past equal values)

Algorithm (Pseudo Code)

Introsort looks at a range and first checks its size. A small range is sorted with insertion sort. A larger range is partitioned as in QuickSort: a random value becomes the pivot and is moved to the end, every value not larger than the pivot is swapped to the front, and the pivot is swapped into the slot right after them, its final place. Before partitioning, Introsort checks the depth budget. If the budget is used up, it doesn’t partition at all, but sorts the whole range with heap sort.

After a partition, the right part is sorted the same way, with a budget that is one smaller, and then the loop goes back to the start with the left part. Every range ends either in insertion sort or in heap sort, and every pivot is already in its final place, so the whole array ends up sorted.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
sort(array):
    depth = 2 * floor(log2(n))
    introspectiveSort(array, 0, n - 1, depth)

introspectiveSort(array, low, high, depth):
    while high - low > INSERTION_SORT_THRESHOLD:
        if depth == 0:
            heapSort(array, low, high)
            return
        pivotIndex = partition(array, low, high)
        introspectiveSort(array, pivotIndex + 1, high, depth - 1)
        high = pivotIndex - 1
    insertionSort(array, low, high)

partition(array, low, high):
    swap a random index with high
    pivot = array[high], i = low - 1
    for j = low to high - 1:
        if pivot >= array[j]: i++, swap(i, j)
    swap(i + 1, high)
    return i + 1

After partition, the pivot is in its final place: every value to its left is smaller or equal, and every value to its right is larger.

The while loop is a hand-made tail call. Instead of a second recursive call for the left part, the loop sets high = pivotIndex - 1 and goes round again. That keeps one recursive call per partition, but it is also where the depth gets lost: the loop runs with the same depth it started with.

Visualization

The visualization below follows the Java code line by line, starting with the values 0 to 9 in shuffled order.

On ten values, the code’s settings would never leave insertion sort: INSERTION_SORT_THRESHOLD = 16 means any range of up to 17 values is insertion sorted. The visualization therefore starts with a threshold of 2 and a depth limit of 1, so all three algorithms appear: one partition, then heap sort on a part that runs out of depth, then insertion sort on a small part. Use the footer to try the code’s own values. The random pivots are repeatable: the first run is the same for every reader, and shuffle picks new values and new pivots.

Each step shows the array, the key in insertion sort, 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.
  • Settings: choose INSERTION_SORT_THRESHOLD (2, 4 or 16) and the depth limit (0, 1, 2, or the code’s formula, which gives 6) in the footer.
  • Phase: the line above the array names the method that is running and its range.
  • Pointers: I and J are the i and j of the method that is running. In partition, I is the end of the values not larger than the pivot and J is the value being checked. In heapify, I is the heap node being fixed. In insertionSort, I is where the key came from and J is the value it is compared with.
  • Colours: the pivot, the key and the values being compared are amber, values being swapped or shifted are salmon, and values in their final place turn green.
  • Boundary: the gray bar marks the end of the part that is done so far within the range: the values not larger than the pivot in partition, the heap in heapSort, and the sorted part in insertionSort.
pivot / key / compared swap / shift final place I = i J = j

Java Code

The implementation is an IntrospectiveSort class with one public method, sort, and five private methods: introspectiveSort drives the loop and the recursion, partition splits a range around a random pivot, insertionSort handles small ranges, and heapSort and heapify provide the fallback. The size threshold is the constant INSERTION_SORT_THRESHOLD = 16. Three small helpers, swap, greater and greaterOrEqual, live in a separate SortUtils class.

The complete code is in the algorithm-examples repository on GitHub: IntrospectiveSort.java, with the helpers in SortUtils.java.

sort

1
2
3
4
5
6
7
8
9
@Override
public <T extends Comparable<T>> T[] sort(T[] array) {
    if (array == null || array.length <= 1) {
        return array;
    }
    final int depth = 2 * (int) (Math.log(array.length) / Math.log(2));
    introspectiveSort(array, 0, array.length - 1, depth);
    return array;
}

sort is the entry point. It accepts an array of any Comparable type, such as Integer or String, and returns null, an empty array or a single value straight back. Otherwise it computes the depth limit, $2 \lfloor \log_2 n \rfloor$, and calls introspectiveSort on the full range. Java has no log2 method, so the code divides the natural logarithm by Math.log(2) and casts the result down to an int.

introspectiveSort

1
2
3
4
5
6
7
8
9
10
11
12
private static <T extends Comparable<T>> void introspectiveSort(T[] array, final int low, int high, final int depth) {
    while (high - low > INSERTION_SORT_THRESHOLD) {
        if (depth == 0) {
            heapSort(array, low, high);
            return;
        }
        final int pivotIndex = partition(array, low, high);
        introspectiveSort(array, pivotIndex + 1, high, depth - 1);
        high = pivotIndex - 1;
    }
    insertionSort(array, low, high);
}

introspectiveSort decides which algorithm sorts the range [low .. high]. While the range has more than INSERTION_SORT_THRESHOLD + 1 values, it either hands the whole range to heapSort, when the depth budget is used up, or partitions it. After a partition, the right part is sorted recursively with one less depth, and the loop continues with the left part by moving high. When the range is small enough, the loop ends and insertionSort finishes it.

depth is final, so the loop runs on the left part with the same depth again and again. Only the right parts count down towards heap sort. If the pivot keeps landing at the right end, the left part shrinks by one value per pass and heap sort never takes over. That is exactly what happens on an array of equal values: partition sends every equal value to the left, so 32,000 equal values take about 512 million comparisons, where 32,000 random values take about 620,000. Decrementing depth once per pass of the loop (make it non-final, add depth--; before partition, and pass depth to the recursive call) restores the guarantee: the same 32,000 equal values then take about 1 million comparisons, with heap sort taking over.

partition

1
2
3
4
5
6
7
8
9
10
11
12
13
14
private static <T extends Comparable<T>> int partition(T[] array, final int low, final int high) {
    final int pivotIndex = low + (int) (Math.random() * (high - low + 1));
    SortUtils.swap(array, pivotIndex, high);
    final T pivot = array[high];
    int i = low - 1;
    for (int j = low; j < high; j++) {
        if (SortUtils.greaterOrEqual(pivot, array[j])) {
            i++;
            SortUtils.swap(array, i, j);
        }
    }
    SortUtils.swap(array, i + 1, high);
    return i + 1;
}

partition is a Lomuto partition with a random pivot. A random index in the range is swapped to high, and that value becomes the pivot. j then walks from low to high - 1, and every value that is not larger than the pivot is swapped to the front, growing the region [low .. i]. Finally the pivot is swapped into i + 1, just after that region, and its index is returned.

Two details are worth noticing:

  • The random pivot makes a bad split on sorted or reverse-sorted input very unlikely, so on most inputs the depth limit is never reached. It also means the steps differ from run to run, even for the same array.
  • The test is pivot >= array[j], so values equal to the pivot all go to the left. With many duplicates, the pivot ends up near the right end and the split is very uneven. Combined with the depth issue above, that is what makes equal values quadratic.

insertionSort

1
2
3
4
5
6
7
8
9
10
11
private static <T extends Comparable<T>> void insertionSort(T[] array, final int low, final int high) {
    for (int i = low + 1; i <= high; i++) {
        final T key = array[i];
        int j = i - 1;
        while (j >= low && SortUtils.greater(array[j], key)) {
            array[j + 1] = array[j];
            j--;
        }
        array[j + 1] = key;
    }
}

insertionSort sorts the small range [low .. high], with both ends inclusive. Each value from low + 1 onwards is taken out as the key, the larger values before it shift one position right, and the key drops into the gap. The loop stops at low, so it never reaches outside the range. The Insertion Sort guide explains it step by step.

heapSort and heapify

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
private static <T extends Comparable<T>> void heapSort(T[] array, final int low, final int high) {
    final int n = high - low + 1;
    for (int i = (n / 2) - 1; i >= 0; i--) {
        heapify(array, i, n, low);
    }
    for (int i = high; i > low; i--) {
        SortUtils.swap(array, low, i);
        heapify(array, 0, i - low, low);
    }
}

private static <T extends Comparable<T>> void heapify(T[] array, final int i, final int n, final int low) {
    final int left = 2 * i + 1;
    final int right = 2 * i + 2;
    int largest = i;

    if (left < n && SortUtils.greater(array[low + left], array[low + largest])) {
        largest = left;
    }
    if (right < n && SortUtils.greater(array[low + right], array[low + largest])) {
        largest = right;
    }
    if (largest != i) {
        SortUtils.swap(array, low + i, low + largest);
        heapify(array, largest, n, low);
    }
}

heapSort is the fallback, and it sorts only [low .. high]. The heap uses positions 0 to n - 1 relative to low, so node i lives at array[low + i] and its children at low + 2i + 1 and low + 2i + 2. The first loop builds a max-heap from the bottom up. The second loop repeatedly swaps the root, the largest value, to the end of the heap, where it is in its final place, and shrinks the heap by one.

heapify restores the heap below node i: it finds the largest of the node and its two children, and if a child is larger, swaps it up and continues from that child. The Heap Sort guide shows the same steps as a tree.

swap, greater and greaterOrEqual

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public static <T> void swap(T[] array, int i, int j) {
    if (i != j) {
        final T temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }
}

public static <T extends Comparable<T>> boolean greater(T firstElement, T secondElement) {
    return firstElement.compareTo(secondElement) > 0;
}

public static <T extends Comparable<T>> boolean greaterOrEqual(T firstElement, T secondElement) {
    return firstElement.compareTo(secondElement) >= 0;
}

These helpers from SortUtils keep the three algorithms easy to read. swap exchanges two elements, and skips the work when both indices are the same. greater and greaterOrEqual compare two elements with 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 IntrospectiveSort().sort(numbers);
System.out.println(Arrays.toString(numbers));
// [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Create an IntrospectiveSort, pass it an array, and the same array comes back sorted. With ten values and a threshold of 16, this example never partitions: the whole array goes straight to insertionSort.

Summary

  • Introsort is a hybrid sort: QuickSort by default, heap sort when the recursion gets too deep, and insertion sort for small ranges.
  • This implementation uses a random Lomuto pivot, sorts the right part recursively and loops on the left part, with a depth limit of $2 \lfloor \log_2 n \rfloor$ and insertion sort for ranges of up to 17 values.
  • After each partition, the pivot is in its final place, and every range ends in either insertion sort or heap sort.
  • By design it runs in $O(n \log n)$ in every case, uses $O(\log n)$ stack space, and sorts in place but is not stable. In this code, the depth isn’t reduced for the left part, so arrays with many equal values can still take $O(n^2)$.
  • In Java, use Arrays.sort(): primitive arrays get a Dual-Pivot QuickSort with a heap sort fallback, and object arrays get the stable TimSort.
This post is licensed under CC BY 4.0 by the author.