Introduction

Bozo sort is a sort that keeps randomly arranging an array until it is sorted. This sort should never been used.

Implementation

We keep checking if the array is sorted and if is not, we pick two random indexes to swap.


Code

boolean sorted(int[] arr) {
  for (int i = 1; i < arr.length; i++) {
    if (arr[i] < arr[i - 1]) {
      return false;
    }
  }
  return true;
}

public void bozoSort(int[] arr) {

  int i = 0;

  // Keep trying until sorted.
  while (!sorted(arr)) {
    // Pick two random positions.
    int x = (int) (Math.random() * arr.length);
    int y = (int) (Math.random() * arr.length);
    // Swap array positions.
    int temp = arr[x];
    arr[x] = arr[y];
    arr[y] = temp;
  }
}