C++ 程式是針對博戈排序還是置換排序?


在這裡,我們將看到另一種稱為 Bogosort 的排序演算法。該排序也稱為置換排序、傻瓜排序、慢速排序等。這種排序演算法是一種特別無效的排序技術。它屬於生成和測試範例。它會反覆生成一個置換,直到排序完成。概念非常直接,即只要列表未排序,就對元素進行洗牌。

演算法

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

更新於: 31-Jul-2019

200 次瀏覽

為你的 職業生涯注入動力

完成課程後即可獲得認證

開始
廣告
© . All rights reserved.