Post

Stooge Sort in Java

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

Stooge Sort in Java

Introduction

Stooge Sort is a recursive comparison sort that is correct, simple, and remarkably slow. It compares the first and last value of a range and swaps them if they are out of order. Then, if the range holds more than two values, it sorts the first two thirds, the last two thirds, and the first two thirds again. The name comes from the Three Stooges, the slapstick comedy act, and the algorithm is a well-known exercise in Introduction to Algorithms by Cormen, Leiserson, Rivest and Stein.

Three ideas carry the whole algorithm:

  • Fix the ends: if the last value of the range is smaller than the first, swap them. For a range of one or two values, that is all there is to do.
  • Overlap the thirds: the two recursive calls on two thirds of the range overlap in the middle third, and that overlap is what carries the largest values to the end.
  • Repeat the first part: after the largest third is in place at the end, the first two thirds are sorted once more to finish the rest.

Stooge Sort is a teaching example, like Bogosort, but of a different kind. Bogosort relies on luck; Stooge Sort is fully deterministic and always finishes. It is a good exercise in proving a recursive algorithm correct, and in solving the recurrence that shows how slow it is.

This article uses Stooge Sort with floor thirds: for a range of length values, third = length / 3, rounded down, so each recursive call covers length - third values, which is two thirds rounded up.

Performance Characteristics

Stooge Sort makes exactly the same calls for every input of the same length: the comparisons don’t depend on the order of the values at all, only the swaps do.

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^{2.71})$An already sorted array: no swaps, but every call still runs
Average$O(n^{2.71})$Random input: the same calls, with some swaps
Worst$O(n^{2.71})$Any input: the number of comparisons is fixed by $n$

Why $n^{2.71}$? Each call does one comparison and then makes three calls on ranges of two thirds of its size, so the work follows the recurrence

\[T(n) = 3\,T(2n/3) + O(1)\]

The number of calls triples at every level while the ranges only shrink by a third, so the bottom level dominates. Solving the recurrence gives $T(n) = O(n^{\log 3 / \log 1.5}) = O(n^{2.7095\ldots})$, which is worse than the $O(n^2)$ of Bubble Sort or Insertion Sort.

With the repository code, 10 values always take 364 comparisons and 1,000 values always take 64,570,081: about 130 times the 499,500 comparisons that Selection Sort makes for the same array. On a laptop, 1,000 random values took about 0.1 seconds, 2,000 about 1 second, and 4,000 about 9 seconds.

Stooge Sort does no less work on sorted input. It has no early exit: an array that is already in order goes through every single call, exactly like a reversed one.

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)$: the recursion goes about $\log_{1.5} n$ calls deep, 17 for 1,000 values
In placeYes
StableNo (the end swap jumps over every value in between, including equal ones)

Algorithm (Pseudo Code)

Stooge Sort sorts a range from start (inclusive) to end (exclusive). It first compares the first and last values of the range, and swaps them if the last one is smaller. A range of one or two values is now sorted.

For a longer range, it works out third, a third of the length rounded down, and makes three recursive calls: on the range without its last third, on the range without its first third, and on the range without its last third again.

1
2
3
4
5
6
7
8
9
10
sort(array, start, end):
    if array[end - 1] < array[start]:
        swap(start, end - 1)
    length = end - start
    if length > 2:
        third = length / 3            (rounded down)
        sort(array, start, end - third)   first two thirds
        sort(array, start + third, end)   last two thirds
        sort(array, start, end - third)   first two thirds again
    return array

Why does this work? Call the largest third values of the range the top values. After the first call, every top value that was in the first two thirds sits at the end of the first two thirds, which lies inside the last two thirds because the middle third is at least as long as the last one. So after the first call, all the top values are in the last two thirds, and the second call sorts them into the last third, in order. They are now final, and the third call sorts everything before them.

The overlap is essential. If the middle third were shorter than the last third, a top value could be stuck in the first third, out of reach of the second call. Rounding the two thirds up (here, by rounding third down) keeps the overlap large enough.

Visualization

The visualization below follows the Java code line by line, starting with the values 0 to 8 in shuffled order. It uses 9 values rather than 10 because 10 values take 364 comparisons, three times as many as 9.

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 which of its parent’s three calls it is. Values outside the current range are faded.
  • Colours: the first and last values of the current range are amber while they are compared, swapped values are salmon, and values in their final place are green.
  • Duplicates: tick Duplicates to sort values between 0 and 2 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.
first and last compared swapped final place current call

Java Code

The implementation is a StoogeSort class with two public methods: sort(array), which sorts the whole array, and sort(array, start, end), which does the recursive work on a range. It uses the less helper from 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: StoogeSort.java, with the helpers in SortUtils.java.

sort

1
2
3
4
5
6
7
8
@Override
public <T extends Comparable<T>> T[] sort(T[] array) {
    if (array.length == 0) {
        return array;
    }
    sort(array, 0, array.length);
    return array;
}

sort accepts an array of any Comparable type and sorts it in place. An empty array returns straight away, because the range method reads array[end - 1] and array[start] before anything else, which would fail on an empty array. Every other array is sorted as one range, from 0 to array.length, with the end exclusive.

sort (range)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public <T extends Comparable<T>> T[] sort(final T[] array, final int start, final int end) {
    if (SortUtils.less(array[end - 1], array[start])) {
        final T temp = array[start];
        array[start] = array[end - 1];
        array[end - 1] = temp;
    }

    final int length = end - start;
    if (length > 2) {
        int third = length / 3;
        sort(array, start, end - third);
        sort(array, start + third, end);
        sort(array, start, end - third);
    }
    return array;
}

The range method follows the pseudo code exactly. It compares the last value of the range with the first and swaps them inline, with a temporary variable, instead of calling SortUtils.swap like the other classes in the repository. Integer division rounds third down, so each recursive call covers length - third values, two thirds rounded up, and the overlap stays large enough.

Every call makes exactly one comparison, so the number of comparisons equals the number of calls. A call on two values compares them and stops, and the recursion never reaches a range of one value, except when the whole array holds a single value: then sort compares that value with itself, harmlessly.

The range method is public, but it doesn’t check its arguments. sort(array, 0, 0) throws an ArrayIndexOutOfBoundsException for array[-1], and a range with start after end makes one comparison and returns the array unchanged, without any error. Its return value is also never used by the recursion.

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 keeps the code easy to read. less returns true when the first element is smaller than the second, using compareTo, so the algorithm works for any type that implements Comparable. Because it is strict, equal values at the two ends are never swapped, but a swap of unequal ends still jumps over any equal values in between. Sorting the values 1, 1, 0 swaps the first 1 with the 0 straight away, and the two 1s end up in the opposite order.

Running it

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

Create a StoogeSort, pass it an array, and the same array comes back sorted, after 364 comparisons and 20 swaps. Any order of 10 values takes the same 364 comparisons. The array holds Integer, not int, because the method works with Comparable objects.

Summary

  • Stooge Sort fixes the ends of a range, then recursively sorts the first two thirds, the last two thirds, and the first two thirds again.
  • The overlap between the two thirds carries the largest values to the end, which makes the algorithm correct.
  • It always makes the same number of comparisons for the same $n$, which grows as $O(n^{2.71})$: slower than any quadratic sort.
  • It needs $O(\log n)$ space for the recursion, and is in place but not stable.
  • It is a lesson in recursion and recurrences, not a sort to use: Merge Sort, which also splits the array and recurses, makes $O(n \log n)$ comparisons.
This post is licensed under CC BY 4.0 by the author.