Post

Tournament Sort in Java

Learn how Tournament Sort 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.

Tournament Sort in Java

Introduction

Tournament Sort is a comparison sort that works like a knockout tournament. All values enter a bracket; in every match the smaller value goes through to the next round, and the winner of the final is the smallest value. That champion goes to the output, its place in the bracket is emptied, and only the matches it played are replayed to find the next champion.

Three ideas carry the whole algorithm:

  • Winner tree: a complete binary tree with the values as leaves; every internal node holds the winner, the smaller value, of its two children. The root holds the smallest value of all.
  • Replay the path: after the champion is removed, only the nodes on the path from its leaf to the root can change, so only $\log_2 n$ matches are replayed, not the whole tournament.
  • Indices, not values: each node stores the index of the winning value in the original array, so the values never move until they are written to the output.

Tournament Sort is closely related to Heap Sort: both use a binary tree to find the next smallest value in $O(\log n)$. Its real home is external sorting, sorting data too large for memory. There, a variant called replacement selection uses a tournament tree to produce sorted runs on disk that are, on average, twice as long as the memory, which makes the later merge passes cheaper.

This article uses Tournament Sort with an array-based winner tree of indices: the leaves are padded to the next power of two with empty slots, the champions are collected in a result array, and the result is copied back at the end.

Performance Characteristics

Tournament Sort plays a fixed number of matches for a given size: building the tree takes one match per internal node, and every extraction replays one path.

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)$Any input: every champion replays its full path to the root
Average$O(n \log n)$Any input
Worst$O(n \log n)$Any input; padding up to a power of two adds at most one more level

Why $n \log n$? Building the tree plays $n - 1$ matches, one for every internal node that has two contestants. Each of the $n$ extractions then replays the matches on one path from a leaf to the root, which has $\log_2$ of the leaf count nodes. Matches against an empty slot need no comparison, so the real count is a little lower: with the repository code, about $0.87 \, n \log_2 n$ comparisons for 1,000 random values, and 24 for the ten values of the visualization.

Tournament Sort makes fewer comparisons than heap sort, because each replay compares only one pair per level, while heap sort’s sift-down compares the node with both children. In exchange, it needs a tree of size about $2n$ to $4n$ and an output array, where heap sort works in place.

Space Complexity

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

PropertyValue
Space$O(n)$: an int tree of twice the padded size, plus a result array of the same length as the input
In placeNo (the sorted values are collected in a separate array and copied back)
StableYes (on a tie, the left contestant, which has the lower index, wins)

Algorithm (Pseudo Code)

Tournament Sort first sets up the bracket. The number of leaf slots is rounded up to a power of two, the values go into the first slots, and the rest stay empty. Then the matches are played bottom-up: every internal node compares the winners of its two children and keeps the smaller one. A value facing an empty slot goes through without a match. After the last round, the root holds the smallest value.

Then the sorting begins. The champion at the root is written to the next position of the output, and its leaf is emptied. Only the nodes on the path from that leaf to the root depended on it, so only those matches are replayed, from the bottom up, and the root now holds the next smallest value. This repeats until every value has been written out, smallest first.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
sort(array):
    leafCount = next power of two >= n
    tree = 2 * leafCount slots, all empty
    for i = 0 to n - 1: tree[leafCount + i] = i
    for node = leafCount - 1 down to 1:
        tree[node] = winnerIndex(tree[2 * node], tree[2 * node + 1])
    for out = 0 to n - 1:
        winner = tree[1]
        result[out] = array[winner]
        node = leafCount + winner
        tree[node] = empty
        for node = node / 2 while node >= 1, node = node / 2:
            tree[node] = winnerIndex(tree[2 * node], tree[2 * node + 1])
    copy result into array

winnerIndex(left, right):
    if left is empty: return right
    if right is empty: return left
    return right if array[right] < array[left], else left

Every internal node holds the index of the smallest value among the non-empty leaves below it, so the root always holds the smallest value that hasn’t been output yet.

The tree is stored like a binary heap: node k has its children at 2k and 2k + 1, its parent at k / 2, and the root is node 1. The leaves start at index leafCount, so the leaf of value i is at leafCount + i, which is how the code finds the path to replay.

Visualization

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

Each step shows the winner tree, the result array 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.
  • Tree: the bottom row holds the 16 leaf slots: the ten values and six empty slots, drawn dashed. Every node above shows the value of the winner it holds. The root is amber.
  • Rounds and replays: while the tree is built, each step plays one round of matches. After that, each step removes the champion and replays only the matches on its path; the nodes that were just decided are salmon.
  • Result: the row below the tree collects the champions in sorted order. The footer counts the comparisons.
champion just decided in the result empty slot

Java Code

The implementation is a TournamentSort class with one public method, sort, and two private helpers: nextPowerOfTwo rounds the leaf count up, and winnerIndex plays one match between two indices. The tree is a plain int[]. One small helper, less, lives in a separate SortUtils class.

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

sort

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
28
29
30
31
32
33
34
35
36
@Override
public <T extends Comparable<T>> T[] sort(T[] array) {
    if (array == null || array.length < 2) {
        return array;
    }

    final int n = array.length;
    final int leafCount = nextPowerOfTwo(n);

    final int[] tree = new int[2 * leafCount];
    Arrays.fill(tree, -1);

    for (int i = 0; i < n; i++) {
        tree[leafCount + i] = i;
    }

    for (int node = leafCount - 1; node >= 1; node--) {
        tree[node] = winnerIndex(array, tree[node * 2], tree[node * 2 + 1]);
    }

    final T[] result = array.clone();
    for (int out = 0; out < n; out++) {
        final int winner = tree[1];
        result[out] = array[winner];

        int node = leafCount + winner;
        tree[node] = -1;

        for (node /= 2; node >= 1; node /= 2) {
            tree[node] = winnerIndex(array, tree[node * 2], tree[node * 2 + 1]);
        }
    }

    System.arraycopy(result, 0, array, 0, n);
    return array;
}

sort returns null, empty and one-element arrays straight back. Otherwise it sizes the tree: leafCount leaf slots at the end of the int array and leafCount - 1 internal nodes before them, with index 0 unused. Every slot starts at -1, meaning empty, and the first n leaves get the indices 0 to n - 1. The building loop runs from the last internal node back to the root, so every node is filled after both of its children. The extraction loop writes the champion to result, empties its leaf, and walks up with node /= 2, replaying one match per level. Finally the result is copied back into array, which is returned.

Two details are worth noticing:

  • The tree holds indices, not values. A match only compares array[left] and array[right]; nothing in array moves until the final System.arraycopy.
  • array.clone() is only used to get a T[] of the right type and length, since Java can’t create a generic array directly. Its contents are overwritten.

winnerIndex

1
2
3
4
5
6
7
8
9
10
private static <T extends Comparable<T>> int winnerIndex(T[] array, int leftIndex, int rightIndex) {
    if (leftIndex == -1) {
        return rightIndex;
    }
    if (rightIndex == -1) {
        return leftIndex;
    }

    return SortUtils.less(array[rightIndex], array[leftIndex]) ? rightIndex : leftIndex;
}

winnerIndex plays one match. An empty slot loses to anything, without a comparison, and two empty slots give an empty winner. Otherwise the right contestant wins only when it is strictly smaller, so on a tie the left one goes through. Since the left subtree always holds lower indices than the right subtree, equal values leave the tree in their original order, which makes the sort stable; the source comment only says it keeps the ordering “deterministic”, but stability is the more useful consequence.

nextPowerOfTwo

1
2
3
4
5
6
7
private static int nextPowerOfTwo(int n) {
    int power = 1;
    while (power < n) {
        power <<= 1;
    }
    return power;
}

nextPowerOfTwo doubles power until it reaches n, so a perfect binary tree has room for every value. For 10 values that is 16 leaves; for 1,024 values it is exactly 1,024, and for 1,025 values it jumps to 2,048.

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 is the only comparison the class needs: 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 TournamentSort().sort(numbers);
System.out.println(Arrays.toString(numbers));
// [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Create a TournamentSort, pass it an array, and the same array comes back sorted, after 24 comparisons. The array holds Integer, not int, because the method works with Comparable objects.

Summary

  • Tournament Sort is a knockout tournament between the values: a winner tree finds the smallest value, which is output and removed, and only its path is replayed.
  • This implementation stores the tree as an int[] of indices, padded to a power of two with empty slots, and collects the champions in a result array.
  • Every internal node holds the index of the smallest value below it, so the root is always the next value of the sorted output.
  • It runs in $O(n \log n)$ in every case with fewer comparisons than heap sort, needs $O(n)$ extra space, and is stable but not in place.
  • It shines in external sorting, where tournament trees build long sorted runs. In memory, Arrays.sort() is faster, and Heap Sort does the same job in place.
This post is licensed under CC BY 4.0 by the author.