BogoSort也称为置换排序,愚蠢排序,慢速排序,shot弹枪排序或猴子排序是一种基于生成和测试范式的特别无效的算法。该算法会连续生成其输入的排列,直到找到已排序的排列。(Wiki)
例如,如果将bogosort用于对一副纸牌进行排序,则将包括检查该纸牌是否井然有序;如果不是,则将纸牌扔到空中,随机拾起纸牌,然后重复直到对卡片组进行排序为止的过程。
伪代码:
while not Sorted(list) do
shuffle (list)
done
// Java Program to implement BogoSort
public class BogoSort {
// Sorts array a[0..n-1] using Bogo sort
void bogoSort(int[] a)
{
// if array is not sorted then shuffle the
// array again
while (isSorted(a) == false)
shuffle(a);
}
// To generate permuatation of the array
void shuffle(int[] a)
{
// Math.random() returns a double positive
// value, greater than or equal to 0.0 and
// less than 1.0.
for (int i = 0; i < a.length; i++)
swap(a, i, (int)(Math.random() * i));
}
// Swapping 2 elements
void swap(int[] a, int i, int j)
{
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
// To check if array is sorted or not
boolean isSorted(int[] a)
{
for (int i = 1; i < a.length; i++)
if (a[i] < a[i - 1])
return false;
return true;
}
// Prints the array
void printArray(int[] arr)
{
for (int i = 0; i < arr.length; i++)
System.out.print(arr[i] + " ");
System.out.println();
}
public static void main(String[] args)
{
// Enter array to be sorted here
int[] a = { 3, 2, 5, 1, 0, 4 };
BogoSort ob = new BogoSort();
ob.bogoSort(a);
System.out.print("Sorted array: ");
ob.printArray(a);
}
}
输出:
Sorted array: 0 1 2 3 4 5
请参阅有关BogoSort或Permutation Sort的完整文章,以了解更多详细信息!