Post

Bogosort in Java

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

Bogosort in Java

Introduction

Bogosort is a comparison sort that doesn’t sort at all: it guesses. It checks whether the array is in order, and if it isn’t, it shuffles the whole array at random and checks again. Sooner or later one of the shuffles happens to produce the sorted order, and the loop stops. It is also known as permutation sort, stupid sort or monkey sort.

Two ideas carry the whole algorithm:

  • Check: walk along the array and stop at the first pair that is out of order. If there is none, the array is sorted.
  • Shuffle: if the check fails, put the values in a completely new random order, without keeping anything from the last attempt.

Bogosort is a teaching example, not a practical sort. It shows what an algorithm looks like when it makes no use of what it has learned: every shuffle throws away all the order the last one had, so the chance of success never improves. With $n$ different values there are $n!$ possible orders and only one of them is sorted, and that factorial is what makes Bogosort the standard example of a hopeless running time.

This article uses the randomized Bogosort from the repository, which shuffles with a Fisher–Yates shuffle. A deterministic variant that steps through every permutation in turn also exists, but it is not what this code does.

Performance Characteristics

Bogosort’s running time depends on luck. The input only matters in one case: if it is already sorted, the first check succeeds and nothing is shuffled.

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)$An already sorted array: one check of $n - 1$ comparisons and no shuffles
Average$O(n \cdot n!)$Random input with different values: about $n!$ shuffles of $n$ swaps each
WorstUnboundedEvery shuffle can miss the sorted order, so there is no upper limit on the number of shuffles

Why $n!$? Every shuffle produces each of the $n!$ orders with the same probability, $1/n!$, no matter what came before. Waiting for an event with probability $1/n!$ takes $n!$ tries on average. Each shuffle costs $n$ swaps, which gives $O(n \cdot n!)$ work on average.

The comparisons are cheaper than you might expect: a check stops at the first pair out of order, and for a random order that usually happens after one or two pairs. On average a check makes fewer than $e - 1 \approx 1.72$ comparisons, so the total is about $1.72 \cdot n!$ comparisons. With the repository code, 7 values took 8,734 comparisons on average over 2,000 runs, against $7! = 5,040$ shuffles.

The factorial grows so quickly that the numbers soon stop making sense. On a laptop, the repository code sorted 10 values in about 0.14 seconds on average. Each extra value multiplies the work by roughly the number of values, so 12 values take tens of seconds, 14 values about an hour, 15 values more than half a day, and 20 values thousands of years.

The worst case is unbounded, but the sort finishes with probability 1: the chance that it is still running after $k$ shuffles is $(1 - 1/n!)^k$, which shrinks towards 0. It just shrinks very slowly when $n!$ is large.

Space Complexity

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

PropertyValue
Space$O(1)$: a loop index and a random index
In placeYes
StableNo (a shuffle puts equal values in any order)

Algorithm (Pseudo Code)

Bogosort repeats two steps. First it checks the array: it compares each pair of neighbours from left to right, and as soon as a pair is out of order, it knows the array isn’t sorted. If every pair is in order, the array is sorted and the sort is done.

Otherwise it shuffles. For each position from left to right, it picks a random position from that one to the end of the array and swaps the two values. This is the Fisher–Yates shuffle, which gives every one of the $n!$ orders the same chance. Then it checks again.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
sort(array):
    while not isSorted(array):
        shuffle(array)
    return array

isSorted(array):
    for i from 0 to n - 2:
        if array[i + 1] < array[i]: return false
    return true

shuffle(array):
    for i from 0 to n - 1:
        r = random index from i to n - 1
        swap(i, r)

Nothing carries over from one shuffle to the next, so the hundredth shuffle is no more likely to succeed than the first.

Duplicates make Bogosort faster. If a value occurs twice, swapping the two copies gives the same order, so more than one of the $n!$ orders counts as sorted. For the values 1, 0, 1, 0, four of the 24 orders are sorted, and the expected number of shuffles drops from 24 to 6.

Visualization

The visualization below follows the Java code line by line, starting with 4 values in random order.

Each step shows the array, the first pair the check found out of order, 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 and new random shuffles.
  • Values: choose between 3 and 6 values. With 5 or 6 values the run is long, so only the first 30 shuffles and the last two are shown.
  • Colours: during a check, the pairs found in order are green and the first pair out of order is amber. A freshly shuffled array is salmon, and the sorted array at the end is green.
  • Counters: the footer counts the shuffles and comparisons, and the line below it shows the average number of shuffles over 1,000 simulated runs, next to $n!$.
checked in order / sorted first pair out of order just shuffled

Java Code

The implementation is a BogoSort class with one public method, sort, and two private static methods: isSorted, which checks the order, and nextPermutation, which shuffles. Two small helpers, swap and less, 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: BogoSort.java, with the helpers in SortUtils.java.

sort

1
2
3
4
5
6
public <T extends Comparable<T>> T[] sort(T[] array) {
    while (!isSorted(array)) {
        nextPermutation(array);
    }
    return array;
}

sort accepts an array of any Comparable type and sorts it in place. The loop checks first, so an array that is already sorted comes back straight away, without a single shuffle. Empty and one-element arrays count as sorted too.

The method implements SortAlgorithm.sort, but unlike the other classes in the repository, it has no @Override annotation. That doesn’t change how it runs; the annotation only asks the compiler to check that the method really overrides one.

isSorted

1
2
3
4
5
6
7
8
private static <T extends Comparable<T>> boolean isSorted(T[] array) {
    for (int i = 0; i < array.length - 1; i++) {
        if (SortUtils.less(array[i + 1], array[i])) {
            return false;
        }
    }
    return true;
}

isSorted compares each value with the one after it, and returns false as soon as a later value is smaller. Because it uses a strict “less than”, equal neighbours count as in order, so arrays with duplicates can finish. The early return keeps each check cheap on unsorted arrays; only the last, successful check walks the whole array.

nextPermutation

1
2
3
4
5
6
7
8
private static <T> void nextPermutation(T[] array) {
    int length = array.length;

    for (int i = 0; i < array.length; i++) {
        int randomIndex = i + RANDOM.nextInt(length - i);
        SortUtils.swap(array, randomIndex, i);
    }
}

nextPermutation shuffles the array. For each position i, it picks a random index from i to the end and swaps the two values, so position i receives a random value from those not placed yet. This is the Fisher–Yates shuffle, and it makes every order equally likely.

The name is misleading. “Next permutation” usually means the next order in a fixed sequence, as in C++’s std::next_permutation, which would step through every order once and finish after at most $n!$ steps. This method returns a random order instead, as its comment says, so the same order can come up again and again.

The random numbers come from one Random object, RANDOM, shared by every BogoSort in the program. It can’t be given a seed from outside, so a run can’t be repeated, which makes the sort awkward to test for anything but the final result.

swap and less

1
2
3
4
5
6
7
8
9
10
11
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;
}

These helpers from SortUtils keep the code easy to read. swap exchanges two elements, and 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 BogoSort().sort(numbers);
System.out.println(Arrays.toString(numbers));
// [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Create a BogoSort, pass it an array, and the same array comes back sorted. For these 10 values that takes $10! = 3,628,800$ shuffles and about 6 million comparisons on average, though a single run can need many more or far fewer. The array holds Integer, not int, because the method works with Comparable objects.

Don’t pass Bogosort more than about a dozen values. Nothing in the code limits its running time, so a larger array keeps the thread busy for hours or longer.

Summary

  • Bogosort checks whether the array is sorted and, if it isn’t, shuffles it at random and checks again.
  • Every shuffle is independent of the last one, so with $n$ different values it takes about $n!$ shuffles on average.
  • It runs in $O(n)$ on sorted input, $O(n \cdot n!)$ on average, and has no upper bound in the worst case. It needs $O(1)$ extra space, and is in place but not stable.
  • In the repository code, nextPermutation is a random Fisher–Yates shuffle, not a step to the next permutation.
  • It is a lesson in what not to do: any real sort, from Insertion Sort to Arrays.sort(), uses what each comparison tells it.
This post is licensed under CC BY 4.0 by the author.