fork download
  1. #include <iostream>
  2. #include <vector>
  3. #include <algorithm>
  4. #include <random>
  5. #include <chrono>
  6.  
  7. using namespace std;
  8.  
  9. // 检查数组是否已排序
  10. bool isSorted(const vector<int>& arr) {
  11. for (size_t i = 0; i < arr.size() - 1; ++i) {
  12. if (arr[i] > arr[i + 1]) {
  13. return false;
  14. }
  15. }
  16. return true;
  17. }
  18.  
  19. // 猴子排序实现
  20. void bogoSort(vector<int>& arr) {
  21. // 使用时间作为随机种子
  22. unsigned seed = chrono::system_clock::now().time_since_epoch().count();
  23. default_random_engine engine(seed);
  24.  
  25. int attempts = 0; // 记录尝试次数
  26.  
  27. // 当数组未排序时继续打乱
  28. while (!isSorted(arr)) {
  29. // 随机打乱数组
  30. shuffle(arr.begin(), arr.end(), engine);
  31. attempts++;
  32.  
  33. // 每10000次尝试打印一次进度(可选)
  34. if (attempts % 10000 == 0) {
  35. cout << "已尝试 " << attempts << " 次..." << endl;
  36. }
  37. }
  38.  
  39. cout << "排序完成!总共尝试了 " << attempts << " 次。" << endl;
  40. }
  41.  
  42. int main() {
  43. vector<int> arr = {5, 2, 9, 1, 5, 6};
  44.  
  45. cout << "排序前: ";
  46. for (int num : arr) {
  47. cout << num << " ";
  48. }
  49. cout << endl;
  50.  
  51. bogoSort(arr);
  52.  
  53. cout << "排序后: ";
  54. for (int num : arr) {
  55. cout << num << " ";
  56. }
  57. cout << endl;
  58.  
  59. return 0;
  60. }
Success #stdin #stdout 0.01s 5276KB
stdin
Standard input is empty
stdout
排序前: 5 2 9 1 5 6 
排序完成!总共尝试了 1495 次。
排序后: 1 2 5 5 6 9