Smooth Sort in Java
Learn how Smooth 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.
Introduction
Smooth Sort is a comparison sort and an adaptive variant of heap sort, invented by Edsger Dijkstra in 1981. Like heap sort, it builds a heap and then repeatedly removes the largest value. Unlike heap sort, it uses a forest of special heaps, which makes it run in $O(n)$ time on data that is already sorted, while still guaranteeing $O(n \log n)$ in the worst case.
Three ideas carry the whole algorithm:
- Leonardo numbers: $L(0) = L(1) = 1$ and $L(k + 2) = L(k + 1) + L(k) + 1$, giving 1, 1, 3, 5, 9, 15, 25, …. A Leonardo tree of order $k$ has $L(k)$ nodes: a root with two subtrees of orders $k - 1$ and $k - 2$.
- A forest stored in the array: the array is split into consecutive Leonardo trees, from large on the left to small on the right. Each tree occupies one contiguous slice, with its root at the right end, and every root is at least as large as its children.
- Ordered roots: the roots of the trees increase from left to right, so the largest value of the whole heap is always the rightmost root, right at the end of the heap region, exactly where the next sorted value belongs.
Heap sort always takes $O(n \log n)$ time, even on a sorted array, because building and dismantling a binary heap moves values back and forth. Smooth Sort’s forest grows from left to right and shrinks from right to left, so when the input is already in order, almost nothing has to move. It is admired more than used, because the code is subtle, but it remains the best-known sort that is both in place and adaptive with an $O(n \log n)$ worst case.
This article uses Smooth Sort with the forest shape stored as a bit vector (p, pshift), with sift restoring the heap inside one tree and trinkle restoring the order of the roots.
Performance Characteristics
Smooth Sort’s running time depends on how sorted the input already is: the closer it is to sorted, the less sifting and trinkling the forest needs.
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)$ | An already sorted array: every new root is already the largest, so nothing moves |
| Average | $O(n \log n)$ | Random input |
| Worst | $O(n \log n)$ | Any input: every tree is $O(\log n)$ deep, and there are $O(\log n)$ trees |
Why $n \log n$ at worst? A Leonardo tree of order $k$ is about $k$ levels deep, and since Leonardo numbers grow like the Fibonacci numbers, $k$ is $O(\log n)$. The forest never holds more than $O(\log n)$ trees. Each insertion or removal sifts down one tree and trinkles along the roots, so each costs $O(\log n)$. On sorted input, each new value is already the largest, so every sift and trinkle stops after a comparison or two. With the repository code, 100,000 sorted values take about 200,000 comparisons, $2n$, against about 4.4 million for random values.
Adaptivity is Smooth Sort’s selling point, but it only kicks in for data that is sorted or nearly sorted. On random data it makes more comparisons than heap sort and is slower than a well-tuned QuickSort or merge sort.
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(1)$: the forest’s shape fits in one long and an int; the Leonardo numbers are a constant table |
| In place | Yes |
| Stable | No (sifting moves values past equal values) |
Algorithm (Pseudo Code)
Smooth Sort works in two phases. In the first, it grows the forest from left to right, one value at a time. If the two rightmost trees have consecutive orders, the new value becomes the root of a tree that combines them; otherwise it starts a new tree of size 1. Before that happens, the tree that was just finished is fixed: sift moves its largest value up to its root, and when the tree will not be merged again, trinkle also moves its root to the left past any larger roots, so that the roots stay in increasing order.
In the second phase, the forest shrinks from right to left. The rightmost root is the largest value in the heap, and it is already at the last position of the heap region, so it is simply left there, and the heap shrinks by one. If that root had children, its two subtrees become separate trees, and trinkle puts their roots back in order. When the last tree is gone, the array is sorted.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
sort(array):
forest = one tree of order 1 holding array[0]
for head = 0 to n - 2: // phase 1: grow
if the two rightmost trees have consecutive orders:
sift(tree at head); merge them, plus array[head + 1], into one tree
else:
if this tree won't be merged again: trinkle(tree at head)
else: sift(tree at head)
add array[head + 1] as a new tree of size 1
trinkle(tree at n - 1)
for head = n - 1 down to 1: // phase 2: shrink
if the rightmost tree has size 1: drop it
else: split it into its two subtrees; trinkle both new roots
sift(tree): move the root down, swapping with the larger child, until it is not smaller than both
trinkle(tree): while the root to the left is larger than this root (and its children), swap roots and continue left;
then sift the tree where the value ends up
After phase 1, the roots of the trees increase from left to right and every tree is a max-heap, so the largest value in the heap is always at the right end of the heap region.
The forest’s shape is stored in two numbers.
pshiftis the order of the rightmost tree, and the bits ofpsay which orders are present: bitiset means there is a tree of orderpshift + i. Merging, splitting and adding trees are then just a few shifts, so the whole forest costs $O(1)$ memory.
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 array, the forest of Leonardo trees drawn above it, 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.
- Forest: each node sits above its array position, and the roots of the trees, which are on top, are amber. A tree’s nodes always form one contiguous slice of the array, with the root at its right end.
- Colours: values that changed in the last step are salmon, the largest value about to leave the heap is amber, and values in their final place on the right are green. In phase 1, values that haven’t joined the forest yet fade out.
- Sorted input: tick Sorted input to start from
[0, 1, …, 9]and watch the comparison count stay low. - Comparisons: the footer shows the phase, the number of trees, and the comparisons so far.
Java Code
The implementation is a SmoothSort class with one public method, sort, and two private methods: sift restores the heap order inside one Leonardo tree, and trinkle restores the order of the roots, moving a root to the left past larger roots and then sifting. A constant table, LEONARDO, holds every Leonardo number that fits in an int. One small helper, less, lives in a separate SortUtils class.
The complete code is in the algorithm-examples repository on GitHub:
SmoothSort.java, with the helpers inSortUtils.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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
@Override
public <T extends Comparable<T>> T[] sort(final T[] array) {
if (array.length < 2) {
return array;
}
final int last = array.length - 1;
long p = 1L;
int pshift = 1;
int head = 0;
while (head < last) {
if ((p & 3L) == 3L) {
sift(array, pshift, head);
p >>>= 2;
pshift += 2;
} else {
if (LEONARDO[pshift - 1] >= last - head) {
trinkle(array, p, pshift, head, false);
} else {
sift(array, pshift, head);
}
if (pshift == 1) {
p <<= 1;
pshift = 0;
} else {
p <<= (pshift - 1);
pshift = 1;
}
}
p |= 1L;
head++;
}
trinkle(array, p, pshift, head, false);
while (pshift != 1 || p != 1L) {
if (pshift <= 1) {
final long mask = p & ~1L;
final int shift = Long.numberOfTrailingZeros(mask);
p >>>= shift;
pshift += shift;
} else {
p <<= 2;
p ^= 7L;
pshift -= 2;
trinkle(array, p >>> 1, pshift + 1, head - LEONARDO[pshift] - 1, true);
trinkle(array, p, pshift, head - 1, true);
}
head--;
}
return array;
}
sort runs both phases. In phase 1, head is the root of the rightmost tree. When the two lowest bits of p are both set, the two rightmost trees have consecutive orders: the tree at head is sifted, and shifting p right by two while adding 2 to pshift replaces them with one tree two orders higher, whose root will be the next value. Otherwise the tree at head is trinkled if it is too big to be merged again (LEONARDO[pshift - 1] >= last - head) and only sifted if it will be merged later, and the next value starts a new tree of order 1, or of order 0 if order 1 is already in use. p |= 1L records the new rightmost tree.
In phase 2, each round removes the root at head, which is already the largest value in the heap. If the rightmost tree has only one node, the next tree to the left becomes the rightmost: numberOfTrailingZeros finds its order. Otherwise the tree splits into its two subtrees, p and pshift are updated to describe them, and both new roots are trinkled; trusty = true tells trinkle that their own subtrees are already valid heaps.
Two details are worth noticing:
- Phase 1 sifts a tree just before it is merged or closed, not right after its root is added. Fixing each tree once, at that moment, is part of what makes sorted input cheap.
- The
LEONARDOtable goes up to 1,402,817,465, the largest Leonardo number belowInteger.MAX_VALUE, so every array that fits in Java can be described.
sift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
private static <T extends Comparable<T>> void sift(final T[] array, int order, int root) {
final T value = array[root];
while (order > 1) {
final int right = root - 1;
final int left = root - 1 - LEONARDO[order - 2];
if (!SortUtils.less(value, array[left]) && !SortUtils.less(value, array[right])) {
break;
}
if (!SortUtils.less(array[left], array[right])) {
array[root] = array[left];
root = left;
order -= 1;
} else {
array[root] = array[right];
root = right;
order -= 2;
}
}
array[root] = value;
}
sift is the Leonardo-tree version of heap sort’s sift-down. A tree of order order with its root at root has its right subtree, of order order - 2, ending just before the root, and its left subtree, of order order - 1, ending L(order - 2) positions further left. If the value is smaller than one of the two child roots, the larger child moves up into the root’s place, and the search continues in that child’s tree. Trees of order 0 and 1 have no children, which ends the loop. The value is held in a variable and written only once, at the end.
trinkle
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
private static <T extends Comparable<T>> void trinkle(final T[] array, long p, int order, int root, boolean trusty) {
final T value = array[root];
while (p != 1L) {
final int stepson = root - LEONARDO[order];
if (!SortUtils.less(value, array[stepson])) {
break;
}
if (!trusty && order > 1) {
final int right = root - 1;
final int left = root - 1 - LEONARDO[order - 2];
if (!SortUtils.less(array[right], array[stepson]) || !SortUtils.less(array[left], array[stepson])) {
break;
}
}
array[root] = array[stepson];
root = stepson;
final long mask = p & ~1L;
final int shift = Long.numberOfTrailingZeros(mask);
p >>>= shift;
order += shift;
trusty = false;
}
if (!trusty) {
array[root] = value;
sift(array, order, root);
}
}
trinkle keeps the roots in increasing order. The root of the previous tree to the left, Dijkstra’s stepson, is L(order) positions back. If it is larger than this root, and larger than this root’s two children, the stepson’s value moves right into this root’s place, and the walk continues one tree further left; the bits of p tell how far. When the walk stops, the value is written down and sift restores the heap order of the tree it ended up in.
The child check is what makes
trinklecorrect: the value that moves right must end up as the largest in its new tree, so it can only replace a root whose children are both smaller.trustyskips that check, and the finalsift, when the caller knows the tree below is already a valid heap and nothing moved.
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 SmoothSort().sort(numbers);
System.out.println(Arrays.toString(numbers));
// [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Create a SmoothSort, pass it an array, and the same array comes back sorted, after 33 comparisons; the same ten values in sorted order need only 14. The array holds Integer, not int, because the method works with Comparable objects.
Summary
- Smooth Sort is an adaptive heap sort: it keeps the heap as a forest of Leonardo trees, each stored as a contiguous slice of the array with its root at the right end.
- This implementation stores the forest’s shape in a bit vector
(p, pshift), usessiftto keep each tree a max-heap andtrinkleto keep the roots in increasing order. - After phase 1, the largest value in the heap is always the rightmost root, already in its final position, so phase 2 only has to shrink the forest from the right.
- It runs in $O(n)$ on sorted input and $O(n \log n)$ in the worst case, needs $O(1)$ extra space, and is in place but not stable.
- Use it when the data is often nearly sorted and memory must stay constant. Otherwise, Heap Sort is simpler, and
Arrays.sort()is faster in practice.
