Bogo Sort
Disclaimer
Bogo sort is not within scope of COMP SCI 300, but was brought up in lecture for fun.
Bogo sort is a highly inefficient sorting algorithm that is not suitable for real-world use. It is a joke algorithm that is used to demonstrate the concept of sorting algorithms. The algorithm works by shuffling the array randomly and checking if it is sorted. If it is not sorted, it shuffles the array again and repeats the process until the array is sorted.
Features
- Stable sorting algorithm
- In-place sorting algorithm
Implementation
Pseudocode
procedure bogoSort(A : list of sortable items)
while not isSorted(A) do
shuffle(A)
end while
end procedure
Java
public static void bogoSort(int[] arr) {
while (!isSorted(arr)) {
shuffle(arr);
}
}
public static boolean isSorted(int[] arr) {
for (int i = 1; i < arr.length; i++) {
if (arr[i - 1] > arr[i]) {
return false;
}
}
return true;
}
public static void shuffle(int[] arr) {
Random rand = new Random();
for (int i = arr.length - 1; i > 0; i--) {
int j = rand.nextInt(i + 1);
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
Runtime Analysis
The time complexity of bogo sort is highly variable and depends on the number of elements in the array and the number of possible permutations. The worst-case time complexity is unbounded, as the algorithm may never sort the array. The average-case time complexity is , where is the number of elements in the array. This makes bogo sort extremely inefficient and impractical for sorting large arrays.
Best Case
The best-case time complexity of bogo sort is , which occurs when the array is already sorted. In this case, the algorithm will make a single pass through the array and return immediately.
Worst Case
The worst-case time complexity of bogo sort is unbounded, as the algorithm may never sort the array. Therefore, the worst-case time complexity is .
Source
The existing course note was retained and normalized during the merge.
Related: Topic index.