Slowsort in Java
Learn how Slowsort 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
Slowsort is a recursive comparison sort designed on purpose to be as slow as possible while still making progress at every step. Andrei Broder and Jorge Stolfi described it in their humorous paper Pessimal Algorithms and Simplexity Analysis, as an example of the “multiply and surrender” paradigm: split a problem into subproblems that are no easier, and keep doing so for as long as possible.
Three ideas carry the whole algorithm:
- Sort both halves: recursively sort the left half and the right half of the range.
- Move the maximum: the largest value of the range is now at the end of one of the halves; compare the two and swap the larger one to the end of the range.
- Sort the rest: recursively sort everything except that last value, which is now in its final place.
Slowsort looks like Merge Sort at first: it splits the range in half and sorts both halves. But instead of merging the halves, it only uses them to find the maximum, and then sorts the remaining $n - 1$ values from scratch, throwing almost all of that work away. In effect it is a recursive Selection Sort where every search for the maximum costs two complete sorts.
Like Stooge Sort, it is deterministic and always finishes, but it grows even faster: its running time is not bounded by any polynomial.
Performance Characteristics
Slowsort makes exactly the same calls for every input of the same length, so its number of comparisons depends only on $n$; only the swaps depend on the order of the values.
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 | $n^{\Theta(\log n)}$ | An already sorted array: no swaps, but every call still runs |
| Average | $n^{\Theta(\log n)}$ | Random input: the same calls, with some swaps |
| Worst | $n^{\Theta(\log n)}$ | Any input: the number of comparisons is fixed by $n$ |
Each call does one comparison and makes three recursive calls: two on the halves and one on all but the last value. That gives the recurrence
\[T(n) = T(\lceil n/2 \rceil) + T(\lfloor n/2 \rfloor) + T(n - 1) + 1\]The third call shrinks the range by only one value, so the recursion barely makes progress. The solution grows faster than any polynomial $n^k$, roughly like $n^{\log_2 n / 2}$. One way to see this is to write the number of comparisons as $n^x$ and watch $x$ grow. With the repository code, $x$ is about 1.9 for 10 values, 3.1 for 100, 4.4 for 1,000 and 5.7 for 10,000.
The numbers start out harmless and then explode:
| Values | Comparisons |
|---|---|
| 10 | 82 |
| 100 | 1,795,978 |
| 300 | about $1.7 \times 10^{9}$ |
| 1,000 | about $1.6 \times 10^{13}$ |
| 10,000 | about $9.5 \times 10^{22}$ |
On a laptop, the repository code sorted 200 random values in about 0.2 seconds, 300 in about 3 seconds, and 400 in about 25 seconds. At that rate, 1,000 values would take about 9 hours, and 2,000 values about five months.
For 10 values Slowsort makes only 82 comparisons, fewer than Stooge Sort’s 364. Small inputs hide how bad it is: the trouble only shows once $n$ grows, which is exactly why asymptotic analysis matters.
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)$: each “all but last” call goes one level deeper, so 100 values go 99 calls deep |
| In place | Yes |
| Stable | No (the swap moves a value past others, including equal ones) |
Algorithm (Pseudo Code)
Slowsort sorts a range from i to j, both inclusive. A range of one value, or an empty range, is already sorted. Otherwise it finds the middle m, and sorts the left half i..m and the right half m+1..j recursively.
Both halves are now sorted, so the largest value of the left half is at m and the largest of the right half is at j. The larger of those two is the largest value of the whole range. If the value at m is larger, it swaps with the value at j. The maximum is now at j, in its final place, so Slowsort finishes by sorting i..j-1.
1
2
3
4
5
6
7
8
sort(array, i, j):
if i >= j: return
m = (i + j) / 2
sort(array, i, m) left half
sort(array, m + 1, j) right half
if array[j] < array[m]:
swap(j, m)
sort(array, i, j - 1) all but the last value
The last call is where the waste comes from. After it moves one value into place, it sorts both halves of the remaining range again, even though they were almost sorted already, and every one of those calls does the same.
Sorting both halves just to find the maximum is the joke. A single scan would find it with $n - 1$ comparisons, which turns Slowsort into Selection Sort and its running time into $O(n^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 array, the stack of recursive calls under 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.
- Call stack: the bars under the array show the range of every call that is running, from the whole array at the top down to the current call, which is outlined. Each bar says whether it is its parent’s left half, right half, or “all but last” call. Values outside the current range are faded.
- Colours: the two half maxima being compared are amber, swapped values are salmon, and values in their final place are green.
- Duplicates: tick Duplicates to sort values between 0 and 3 with repeats. The small number in each cell is its original position, so you can see equal values change order.
- Counters: the footer counts the comparisons and swaps, and shows how deep the recursion is.
Java Code
The implementation is a SlowSort class with one public method, sort, and one private recursive method that sorts a range. Three small helpers, swap, less and greaterOrEqual, live in a separate SortUtils class. The repository notes that the class was taken from TheAlgorithms/Java.
The complete code is in the algorithm-examples repository on GitHub:
SlowSort.java, with the helpers inSortUtils.java.
sort
1
2
3
4
5
@Override
public <T extends Comparable<T>> T[] sort(T[] unsortedArray) {
sort(unsortedArray, 0, unsortedArray.length - 1);
return unsortedArray;
}
sort accepts an array of any Comparable type and sorts it in place, as one range from index 0 to the last index. An empty array needs no special case: the range is 0..-1, and the range method returns straight away.
sort (range)
1
2
3
4
5
6
7
8
9
10
11
12
private <T extends Comparable<T>> void sort(T[] array, int i, int j) {
if (SortUtils.greaterOrEqual(i, j)) {
return;
}
final int m = (i + j) >>> 1;
sort(array, i, m);
sort(array, m + 1, j);
if (SortUtils.less(array[j], array[m])) {
SortUtils.swap(array, j, m);
}
sort(array, i, j - 1);
}
The range method follows the pseudo code exactly. It stops when the range holds at most one value, computes the middle with an unsigned shift, (i + j) >>> 1, which stays correct even if i + j overflows, sorts both halves, moves the larger half maximum to j, and then sorts i..j-1. The swap only happens when the value at j is strictly smaller, so equal maxima stay where they are.
The stop test uses SortUtils.greaterOrEqual(i, j), a helper written for Comparable values, on two int indexes. Java boxes both into Integer objects to call compareTo on every single call. It works, and the comparisons aren’t counted with the array’s comparisons, but a plain i >= j would say the same thing without the boxing.
swap, less 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 less(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 code easy to read. swap exchanges two elements, less returns true when the first element is smaller than the second, and greaterOrEqual returns true when it isn’t. All of them use compareTo, so the algorithm works for any type that implements Comparable.
The swap between m and j moves the value from j back over everything in the right half, and that can include values equal to it. Sorting 1, 0, 0, 0 shows it: the last two zeros come out in the opposite order, so the sort is not stable.
Running it
1
2
3
4
Integer[] numbers = {7, 2, 9, 4, 0, 8, 3, 6, 1, 5};
new SlowSort().sort(numbers);
System.out.println(Arrays.toString(numbers));
// [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Create a SlowSort, pass it an array, and the same array comes back sorted, after 82 comparisons and 26 swaps. Any order of 10 values takes the same 82 comparisons. The array holds Integer, not int, because the method works with Comparable objects.
Summary
- Slowsort sorts both halves of a range, swaps the larger maximum to the end, and then sorts everything but the last value again.
- It was designed as a joke, an example of “multiply and surrender”: every step makes progress, but as little as possible.
- It always makes the same number of comparisons for the same $n$, and that number grows faster than any polynomial, roughly $n^{\log_2 n / 2}$.
- It needs $O(n)$ space for the recursion, and is in place but not stable.
- Finding the maximum with a single scan instead turns it into Selection Sort, and replacing the last step with a merge turns it into Merge Sort.
