Skip to content

Bozo Sort 🀑

BozoSort is a super inefficient sorting algorithm based on randomly swapping items until they are in order. It’s even less efficient than BogoSort, making it a purely theoretical algorithm.


⚠️ Warning

Using BozoSort in real-world applications is strongly discouraged. It’s purely for educational or entertainment purposes.


🧠 How It Works

  1. Swap: Randomly select two elements and swap them.
  2. Check: Verify if the array is sorted.
  3. Repeat: If not sorted, repeat the process.

πŸ–₯️ Workflow Example

Initial Array: [3, 1, 2]

  1. Swap indices 0 and 2 β†’ [2, 1, 3] (not sorted)
  2. Swap indices 1 and 2 β†’ [2, 3, 1] (not sorted)
  3. Swap indices 0 and 1 β†’ [3, 2, 1] (not sorted)
  4. Swap indices 1 and 2 β†’ [3, 1, 2] (not sorted)
  5. Swap indices 0 and 1 β†’ [1, 3, 2] (not sorted)
  6. Swap indices 1 and 2 β†’ [1, 2, 3] (sorted!)

πŸ“Š Visualization


graph TD
    A[Unsorted Array] --> B[Swap Two Random Elements]
    B --> C{Is Sorted?}
    C -->|No| B
    C -->|Yes| D[Sorted Array]

βš–οΈ Comparison with Other Algorithms

Algorithm Time Complexity Practical Use
BozoSort O(n!) Never
BogoSort O(n!) Never
QuickSort O(n log n) Commonly used
BubbleSort O(nΒ²) Rarely used

βš™οΈ Implementation

BozoSort.java
public class BozoSort {
    private static final Random random = new Random();

    public static void bozoSort(ArrayList<Integer> array) {
        while (!isSorted(array)) {
            int index1 = random.nextInt(array.size());
            int index2 = random.nextInt(array.size());
            swap(array, index1, index2);
        }
    }

    private static boolean isSorted(ArrayList<Integer> list) {
        for (int i = 0; i < list.size() - 1; i++) {
            if (list.get(i) > list.get(i + 1)) {
                return false;
            }
        }
        return true;
    }

    private static void swap(ArrayList<Integer> list, int i, int j) {
        int temp = list.get(i);
        list.set(i, list.get(j));
        list.set(j, temp);
    }
}

🚨 Important Notes

  • ⏳ Time Complexity: O(n!) (extremely inefficient).
  • πŸ›‘ Practical Use: Never use in productionβ€”this is a theoretical implementation.
  • πŸ”„ Difference from BogoSort:
  • BozoSort swaps two random elements per iteration.
  • BogoSort shuffles the entire array per iteration.
  • βœ… Edge Cases:
  • For empty lists or single-element lists, the sort completes immediately.

πŸ€” Why Does This Exist?

BozoSort, like BogoSort, is primarily used as a joke algorithm or for educational purposes. It’s a fun way to demonstrate the worst-case scenario in sorting algorithms and the concept of randomized algorithms.


✨ When you want to sort, but also want to embrace chaosβ€”one swap at a time. ✨