function bogoSort(array: number[]) { while (!isSorted(array)) {shuffle(array);
}
}
function isSorted(array: number[]) {for (let i = 1; i < array.length; i++) if (array[i - 1] > array[i]) return false;
return true;
}
function shuffle(array: number[]) {for (let i = array.length - 1; i > 0; i--) swap(array, i, Math.floor(Math.random() * (i + 1)));
}
Start: 4 values in random order. Bogo sort shuffles until the array happens to be sorted; with 4 values that takes 24 shuffles on average (n! = 24).
Understanding Bogo sort
The idea
Bogo sort checks whether the array is sorted and, if not, shuffles it at random and checks again. Every shuffle is one of the n! permutations, exactly one of which is sorted, so on average it takes n! shuffles: 24 for four values, 3.6 million for ten, more than the age of the universe for twenty.
It is a real algorithm in the sense that it terminates with probability 1, and a useless one in every other sense. Its value is as a baseline: any idea that beats it is progress, and its analysis is a clean exercise in expected running time. The deterministic cousin, which tries every permutation in order, is called permutation sort.
The four stages
Complexity
Versus its siblings
Pseudocode
BOGOSORT(array)
while not ISSORTED(array)
SHUFFLE(array)
ISSORTED(array): every array[i − 1] ≤ array[i]
SHUFFLE(array): for i from n − 1 down to 1, swap array[i] with array[random in 0..i]
When to use
Pitfalls
History
The name is a play on bogus; the Jargon File lists it under bogo-sort as a synonym for any hopelessly bad algorithm. Hermann Gruber, Markus Holzer and Oliver Ruepp analysed it seriously in 2007 in 'Sorting the slow way', proving the expected n · n! running time and studying even worse variants.