Post

Tree Sort in Java

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

Tree Sort in Java

Introduction

Tree Sort is a comparison sort built on a data structure. It inserts every value into a binary search tree (BST), and then reads the tree back with an in-order traversal, which visits the values in sorted order.

Three ideas carry the whole algorithm:

  • Binary search tree: every node has at most two children; everything in its left subtree is smaller, and everything in its right subtree is larger.
  • In-order traversal: visit the left subtree, then the node itself, then the right subtree. On a BST, that lists the values from smallest to largest.
  • Keyed values: a BST normally keeps only one copy of each value. Pairing every value with its original position makes equal values different, so none are lost, and keeps them in their original order.

Tree Sort shows how a good data structure can do the sorting for you. It is rarely used as a sort on its own, but the same idea is everywhere: Java’s TreeMap and TreeSet keep their contents sorted with a balanced tree, and iterating over them is exactly the in-order traversal. Tree Sort is also online: values can arrive one at a time, and the sorted order is available at any moment.

This article uses Tree Sort with an unbalanced recursive BST and position-keyed values: each value is wrapped in a record with its index, inserted into the tree, and collected by an in-order traversal.

Performance Characteristics

The speed of Tree Sort depends entirely on the shape of the tree, and with an unbalanced tree that shape depends on the order the values arrive in.

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 values arrive in an order that keeps the tree balanced
Average$O(n \log n)$Random order: the expected depth of a random BST is about $2 \ln n$
Worst$O(n^2)$Sorted or reverse-sorted input: every new value goes to the same side, like a list

Why $n \log n$? Inserting a value costs one comparison per level it passes, so it costs the depth of the tree. In a reasonably balanced tree, the depth is about $\log_2 n$, and $n$ insertions cost $O(n \log n)$. The traversal then visits each node once, in $O(n)$. When the input is already sorted, each new value becomes the right child of the previous one, the tree is a chain $n$ levels deep, and the insertions cost $1 + 2 + \ldots + n = O(n^2)$.

A self-balancing tree removes the worst case. Red-black trees and AVL trees keep their depth at $O(\log n)$ whatever the order of the input, so Tree Sort on top of them is always $O(n \log n)$. In Java, inserting into a TreeMap gets you that for free.

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)$ for the tree nodes and the sorted list, plus recursion as deep as the tree: $O(n)$ worst case
In placeNo (every value is copied into a tree node first)
StableYes (equal values are ordered by their original position)

Algorithm (Pseudo Code)

Tree Sort starts with an empty tree and inserts the values one by one, in their original order. Each value starts at the root and walks down: at every node, it goes left if it is smaller than the node and right if it is larger. When the walk reaches an empty spot, the value becomes a new node there. Two equal values are told apart by their position in the input, so the later one always goes to the right of the earlier one.

When every value is in the tree, an in-order traversal reads it back: for each node, first everything in its left subtree, then the node, then everything in its right subtree. Because smaller values are always on the left, this visits all values from smallest to largest, and the sorted list is copied back into the array.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
sort(array):
    tree = empty binary search tree
    for position = 0 to n - 1:
        tree.add((array[position], position))
    sortedList = tree.inorderSort()
    copy the values of sortedList back into array

insert(node, data):
    if node == null: return new Node(data)
    if data < node.data: node.left = insert(node.left, data)
    else if data > node.data: node.right = insert(node.right, data)
    return node

inOrderSort(node, list):
    if node == null: return
    inOrderSort(node.left, list)
    list.add(node.data)
    inOrderSort(node.right, list)

At every node of the tree, all values in the left subtree are smaller and all values in the right subtree are larger, so the in-order traversal produces them in sorted order.

insert does nothing when data equals node.data: a plain BST silently drops duplicates. That is why the values are wrapped with their position first. Without it, sorting [2, 1, 2] would return [1, 2].

Visualization

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

Each step shows the tree, the array, the sorted list and the line of code that is running, with a short explanation of what just happened. Each node is drawn at the horizontal position of its place in the sorted order, so the in-order traversal simply reads the tree from left to right.

  • 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. Different orders build trees of different shapes.
  • Colours: the value being inserted, and the node it is compared with, are amber; a node that is just added or just visited is salmon; and nodes already added to the sorted list are green. The node being worked on has a dark outline.
  • Rows: the top row is the input array; values that are already in the tree fade out. The bottom row is the sorted list built by the traversal.
  • Duplicates: tick Duplicates to sort values between 0 and 4 with repeats. Each node then also shows its position, @p, and equal values are ordered by it.
inserting / compared added / visited in the sorted list

Java Code

The implementation is a TreeSort class with two public methods, sort(array) and sort(list), and two private methods: doTreeSortArray adapts an array to the list version, and doTreeSortList builds the tree and traverses it. A small private record, Keyed, pairs each value with its position. The tree itself is BSTRecursiveGeneric, a recursive binary search tree in the utils package, of which Tree Sort uses add, insert, inorderSort and inOrderSort.

The complete code is in the algorithm-examples repository on GitHub: TreeSort.java, with the tree in BSTRecursiveGeneric.java.

sort

1
2
3
4
5
6
7
8
9
@Override
public <T extends Comparable<T>> T[] sort(T[] unsortedArray) {
    return doTreeSortArray(unsortedArray);
}

@Override
public <T extends Comparable<T>> List<T> sort(List<T> unsortedList) {
    return doTreeSortList(unsortedList);
}

There are two entry points. sort(array) implements the SortAlgorithm interface for arrays, and sort(list) overrides the interface’s default list method, so lists are sorted directly instead of being converted to an array first. Both accept any Comparable type.

doTreeSortArray

1
2
3
4
private <T extends Comparable<T>> T[] doTreeSortArray(T[] unsortedArray) {
    List<T> sortedList = doTreeSortList(Arrays.asList(unsortedArray));
    return sortedList.toArray(unsortedArray);
}

doTreeSortArray reuses the list version. Arrays.asList wraps the array as a list without copying it, and after sorting, toArray(unsortedArray) copies the sorted values back. Because the list has exactly as many elements as the array, toArray writes into the array that was passed in and returns it, so the caller’s array ends up sorted, just like with the in-place sorts.

doTreeSortList

1
2
3
4
5
6
7
8
9
10
11
12
13
14
private <T extends Comparable<T>> List<T> doTreeSortList(Iterable<T> unsortedList) {
    BSTRecursiveGeneric<Keyed<T>> tree = new BSTRecursiveGeneric<>();

    int position = 0;
    for (T element : unsortedList) {
        tree.add(new Keyed<>(element, position++));
    }

    List<T> sortedList = new ArrayList<>();
    for (Keyed<T> keyed : tree.inorderSort()) {
        sortedList.add(keyed.value());
    }
    return sortedList;
}

doTreeSortList does the two phases. It wraps every element in a Keyed record with its position and adds it to a new tree. Then inorderSort returns the records in sorted order, and the method unwraps them into a plain list of values.

Keyed

1
2
3
4
5
6
7
private record Keyed<T extends Comparable<T>>(T value, int position) implements Comparable<Keyed<T>> {
    @Override
    public int compareTo(Keyed<T> other) {
        int byValue = value.compareTo(other.value);
        return byValue != 0 ? byValue : Integer.compare(position, other.position);
    }
}

Keyed is what makes this Tree Sort correct for duplicates. It compares by value first, and only when two values are equal does it compare their positions. Since every position is unique, no two Keyed records are ever equal, so the tree never drops one. And because the earlier position counts as smaller, equal values come out in their original order, which makes the sort stable.

add and insert

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public void add(T data) {
    this.root = insert(this.root, data);
}

private Node<T> insert(Node<T> node, T data) {
    if (node == null) {
        node = new Node<>(data);
    } else if (node.data.compareTo(data) > 0) {
        node.left = insert(node.left, data);
    } else if (node.data.compareTo(data) < 0) {
        node.right = insert(node.right, data);
    }
    return node;
}

add inserts a value starting from the root. insert walks down recursively: if the node’s value is larger, the new value belongs in the left subtree, and if it is smaller, in the right subtree. At an empty spot it creates the new node, and each call returns the (possibly new) subtree root, so the parent can link to it. When the values are equal, nothing happens; with Keyed values that case never occurs.

The tree is not balanced. On sorted input, every value goes to the right of the previous one, and the tree becomes a chain. With the default JVM stack, 10,000 sorted values already take 209 ms, where 100,000 random values take 25 ms, and at 50,000 sorted values the recursive insert throws a StackOverflowError. Shuffling the input first, or using a TreeMap, avoids both problems.

inorderSort and inOrderSort

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public List<T> inorderSort() {
    List<T> sortedList = new ArrayList<>();
    inOrderSort(this.root, sortedList);
    return sortedList;
}

private void inOrderSort(Node<T> node, List<T> sortedList) {
    if (node == null) {
        return;
    }
    if (node.left != null) {
        inOrderSort(node.left, sortedList);
    }
    sortedList.add(node.data);
    if (node.right != null) {
        inOrderSort(node.right, sortedList);
    }
}

inorderSort creates the result list and starts the traversal at the root. inOrderSort adds everything in the left subtree, then the node itself, then everything in the right subtree. Every node is visited exactly once, so the traversal is $O(n)$. The null checks before the recursive calls are not needed, since the method already returns on null, but they save a call per missing child.

Running it

1
2
3
4
Integer[] numbers = {7, 2, 9, 4, 0, 8, 3, 6, 1, 5};
new TreeSort().sort(numbers);
System.out.println(Arrays.toString(numbers));
// [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Create a TreeSort, pass it an array, and the same array comes back sorted, because toArray copies the result into it. The array holds Integer, not int, because the method works with Comparable objects.

Summary

  • Tree Sort is a comparison sort that inserts every value into a binary search tree and reads it back with an in-order traversal.
  • This implementation wraps each value with its position in a Keyed record, so duplicates are kept and equal values stay in order, and uses an unbalanced recursive BST.
  • At every node, smaller values are on the left and larger ones on the right, so the in-order traversal lists them from smallest to largest.
  • It runs in $O(n \log n)$ on average but $O(n^2)$ on sorted input, needs $O(n)$ extra space, and is stable but not in place.
  • To keep the guarantee, use a balanced tree: a TreeMap or TreeSet in Java. To just sort an array, Arrays.sort() is faster and needs no tree.
This post is licensed under CC BY 4.0 by the author.