猴子撈月排序算法 (隨機排序)

RT大佬教的排序算法
平均複雜度O(n!) ;
n=13 基本已經慢到不行了 ,n再大估計幾萬年才能出來;
核心代碼:do { … } while(next_permutation(k,k+n));

#include <bits/stdc++.h>

#define ull unsigned long long
#define ll long long

using namespace std;

const int maxn=100050;
int k[maxn];
bool vis[maxn];

void houzilaosort(int n) {
    bool flag=0;
    while(!flag) {
        do {
            bool f2=0;
            for(int i=0;i<n-1;i++) {
                if(k[i]>k[i+1]) {
                    f2=1;
                    break;
                }
            }
            if(!f2) {
                flag=1;
                break;
            }
        }while(next_permutation(k,k+n));
    }
}

void init(int n) {
    for(int i=0;i<n;i++) {
        k[i]=rand()%900+100;
    }
}

void printnum(int n) {
    for(int i=0;i<n;i++) {
        cout<<k[i]<<" ";
    }
    cout<<endl;
}

int main() {
    ios::sync_with_stdio(false),cin.tie(0),cout.tie(0);
    srand((unsigned)time(NULL));
    int n;
    cin>>n;
    init(n);
    cout<<"Initial: "<<endl;
    for(int i=0;i<n;i++) {
        cout<<k[i]<<" ";
    }
    cout<<endl;
    houzilaosort(n);
    cout<<"After sort: "<<endl;
    printnum(n);
    return 0;
}

發佈了132 篇原創文章 · 獲贊 151 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章