#include <iostream>
#include <vector>
#include <algorithm>
#include <random>
#include <chrono>
#include <cmath> // 用于计算阶乘
using namespace std;
// 计算阶乘(用于时间复杂度估计)
long long factorial(int n) {
if (n <= 1) return 1;
return n * factorial(n - 1);
}
// 检查数组是否已排序
bool isSorted(const vector<int>& arr) {
for (size_t i = 0; i < arr.size() - 1; ++i) {
if (arr[i] > arr[i + 1]) {
return false;
}
}
return true;
}
// 猴子排序(带时间复杂度输出)
void bogoSort(vector<int>& arr) {
auto startTime = chrono::high_resolution_clock::now(); // 记录开始时间
unsigned seed = chrono::system_clock::now().time_since_epoch().count();
default_random_engine engine(seed);
int attempts = 0;
const int n = arr.size();
const long long worstCaseComplexity = factorial(n); // 最坏情况 O(n!)
cout << "猴子排序(Bogo Sort)时间复杂度分析:" << endl;
cout << "数组大小 n = " << n << endl;
cout << "最坏情况时间复杂度: O(n!) = " << worstCaseComplexity << " 次尝试" << endl;
cout << "平均情况时间复杂度: O(n * n!)" << endl;
cout << "----------------------------------" << endl;
while (!isSorted(arr)) {
shuffle(arr.begin(), arr.end(), engine);
attempts++;
// 每10000次尝试输出一次当前状态
if (attempts % 10000 == 0) {
auto currentTime = chrono::high_resolution_clock::now();
auto elapsedTime = chrono::duration_cast<chrono::milliseconds>(currentTime - startTime).count();
cout << "已尝试 " << attempts << " 次 | ";
cout << "当前时间复杂度: O(" << attempts << ") | ";
cout << "已运行时间: " << elapsedTime << " ms" << endl;
}
}
auto endTime = chrono::high_resolution_clock::now();
auto totalTime = chrono::duration_cast<chrono::milliseconds>(endTime - startTime).count();
cout << "----------------------------------" << endl;
cout << "排序完成!" << endl;
cout << "实际尝试次数: " << attempts << endl;
cout << "理论最坏情况尝试次数: O(n!) = " << worstCaseComplexity << endl;
cout << "总运行时间: " << totalTime << " ms" << endl;
}
int main() {
vector<int> arr = {3, 1, 4, 1, 5, 9,4,76,346}; // 测试数组(建议n≤6,否则可能极慢)
cout << "排序前: ";
for (int num : arr) cout << num << " ";
cout << endl;
bogoSort(arr);
cout << "排序后: ";
for (int num : arr) cout << num << " ";
cout << endl;
return 0;
}