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
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP