日本語

JOKE SORTS

Bogo Sort, visualised

Bogo sort is a joke algorithm: check whether the array is sorted, and if not, shuffle the whole array randomly — repeat.

Run Bogo Sort in the visualizer →

Opens the Sorting Cinema visualizer with 8 elements in English.

How it works

  1. Check from the front whether the array is sorted.
  2. If not, shuffle the entire array randomly.
  3. Repeat until sorted (this app caps the number of attempts).

Complexity and stability

Best
O(n)
Average
O(n·n!)
Worst
Unbounded
Extra space
O(1)
Stability
Unstable

If the input is already sorted, only the O(n) check is needed. For random input it must hit the right arrangement among n! possibilities, so the expected cost is O(n·n!) and the worst case is unbounded. This app stops after at most 50,000 shuffles, so it does not always end sorted.

Source of facts: Complexity follows the learning guide's comparison table and text, and this app's implementation.

Trace on a small array

Bogo sort shuffles at random, so there is no fixed trace. The app's shuffle makes every arrangement equally likely (Fisher–Yates): with 3 elements there are 3! = 6 arrangements, so one shuffle sorts the array with probability 1/6. With 8 elements there are 8! = 40,320.

Suitable inputs and caveats

  • A teaching example for feeling inefficiency and thinking about complexity.
  • This app automatically reduces the array to 8 elements for Play and Step; 8 elements have 8! = 40,320 arrangements.
  • When the 50,000-shuffle limit is reached, it can stop while still unsorted.

FAQ

Does bogo sort always finish?

In theory its worst case is unbounded. This app stops after at most 50,000 shuffles, so it does not always end sorted.

Why is it limited to 8 elements?

The number of arrangements, n!, grows explosively. This app reduces the array to 8 elements for Play and Step.