Bogo Sort

Randomly shuffles the array and checks if sorted. Expected time is factorial. Also known as "stupid sort" or "monkey sort". Use with very small arrays only.

Best O(n) Avg O(n*n!) Worst O(∞) Space O(1) Stable No In-place Yes Comparison-based

How it works

Randomly shuffles the array and checks if sorted. Expected time is factorial. Also known as "stupid sort" or "monkey sort". Use with very small arrays only.

Implementation

function bogoSort(arr) {
  function isSorted() {
    for (let i = 1; i < arr.length; i++)
      if (arr[i-1] > arr[i]) return false;
    return true;
  }
  while (!isSorted()) {
    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]];
    }
  }
}