用于BogoSort或置换排序的C ++程序?

在这里,我们将看到另一种称为Bogo Sort的排序算法。这种排序也称为置换排序,愚蠢排序,慢速排序等。这种排序算法特别无效。这属于“生成和测试”范式。它会反复生成排列,直到将其排序为止。这个概念非常简单。在对列表进行排序之前,只需对元素进行随机排序即可。

算法

bogoSort(array,n)

Begin
   while the arr is not sorted, do
      shuffle arr
   done
End

示例

#include<iostream>
#include<cstdlib>
using namespace std;
bool isSorted(int arr[], int n) { //check whether the list is sorted
   or not
   while (--n > 1)
      if (arr[n] < arr[n - 1])
   return false;
return true;
}
void shuffle(int arr[], int n) {
   for (int i = 0; i < n; i++)
      swap(arr[i], arr[rand() % n]);
}
void bogoSort(int arr[], int n){
   while (!isSorted(arr, n))
      shuffle(arr, n);
}
main() {
   int data[] = {54, 74, 98, 5, 98, 32, 20, 13, 35, 40};
   int n = sizeof(data)/sizeof(data[0]);
   cout << "Sorted Sequence ";
   bogoSort(data, n);
   for(int i = 0; i <n;i++){
      cout << data[i] << " ";
   }
}

输出结果

Sorted Sequence 5 13 20 32 35 40 54 74 98 98