Skip to main content
← All posts

Bogo Sort: Mechanism, Complexity Analysis & Interactive Visualizer

Md. Harun-Or-RoshidNov 5, 20268 min readArticle
Bogo Sort: Mechanism, Complexity Analysis & Interactive Visualizer
Rare & Educational · Article 55 of 62

Bogo Sort

The ultimate joke sorting algorithm: shuffles elements randomly and checks if they are sorted, repeating until luck prevails.

How it works

Bogo Sort (also known as Permutation Sort, Random Sort, or Shotgun Sort) is a highly inefficient algorithm designed as a conceptual joke in computer science. Its logic follows a trial-and-error process:

  1. **Sorted Check:** Scan the array from left to right. If every element \(A[i] \le A[i+1]\), the array is sorted. Exit.
  2. **Random Shuffle:** If the array is not sorted, randomly shuffle all elements (using a random permutation algorithm like Fisher-Yates shuffle).
  3. **Repeat:** Loop back to Step 1 and try again.

Because it relies purely on luck, Bogo Sort has no upper bound on execution speed. It can theoretically run forever without ever sorting the array.

Complexity

Best time
O(n)
Average time
O(n · n!)
Worst time
O(∞)
Extra space
O(1)
Stable
No
In-place
Yes
With an average time complexity of **\(O(n \cdot n!)\)**, Bogo Sort is completely unusable for arrays of size larger than 8. An array of size 10 has \(3,628,800\) possible shuffles, requiring millions of attempts to sort!

Interactive visualization

Pseudocode

procedure bogoSort(A):
  while not isSorted(A):
    shuffle(A)
    
function isSorted(A):
  for i from 0 to length(A) - 2:
    if A[i] > A[i+1]:
      return false
  return true

JavaScript implementation

function bogoSort(arr) {
  while (!isSorted(arr)) {
    shuffle(arr);
  }
  return arr;
}

function isSorted(arr) {
  for (let i = 0; i < arr.length - 1; i++) {
    if (arr[i] > arr[i + 1]) return false;
  }
  return true;
}

function shuffle(arr) {
  for (let i = arr.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [arr[i], arr[j]] = [arr[j], arr[i]];
  }
}

Pros and cons

Pros

  • Purely conceptual and highly humorous.
  • Extremely simple logic.
  • Good for validating random number generator performance.

Cons

  • Extremely bad average complexity, worse than exponential.
  • Theoretical worst-case execution is infinite.
  • Unstable sorting order.

When (not) to use it

  • Humorous demonstrations: Fun to show in algorithmic classes to highlight the difference between efficient design and blind search.
  • Real projects: Never under any circumstances.
Up next: Bozo Sort — a similar randomized algorithm that shuffles by swapping a single random pair of elements when the list is unsorted.
Share:
Share on X
Share on LinkedIn
Share on Facebook
Share on Reddit
Share on WhatsApp
Share on Telegram
Copy link

Related reading

Bogo Sort Sorting Algorithm & Guide | Draftsbook · Draftsbook