跳到正文

个人记录

猴子排序(优化版)

sky_of_stars约 3 分钟
原文
文章信息与版本

文章信息

收录
2026年4月10日
更新
2026年4月10日
篇幅
约 3 分钟

版本

  1. v1当前
C++
#include <bits/stdc++.h>
#include <random>
using namespace std;
vector <int> tar,ans;
int n,f;
void monkey_sort(){
	random_shuffle(tar.begin(),tar.end());
	//for(int i:tar){
	//	cout << i << " ";
	//}
	cout << 1;
	vector<int> maxup,tmp,lef;
	int top=-1;
	for(int i=0;i<tar.size();i++){
		if(tar[i]>=top && (tar[i]-top)<=f){
			top=tar[i];
			maxup.push_back(top);
		}else{
			lef.push_back(tar[i]);
		}

	}
	//for(int i:maxup){
	//	cout << i << " ";
	//}
	//cout << endl;
	//for(int i:lef){
	//	cout << i << " ";
	//}
	//merge
	for(int i=0,j=0;i<ans.size() || j<maxup.size();){
		if(i<ans.size() && (j>=maxup.size() || ans[i]<=maxup[j])){
			tmp.push_back(ans[i]);
			i++;
		}else if( j<maxup.size() && (i>=ans.size() || ans[i]>maxup[j])){
			tmp.push_back(maxup[j]);
			j++;
		}
	}
	//cout << endl;
	ans=tmp;tar=lef;
	//for(int i:ans)cout << i << " ";
}
int main() {
	/*ans={1,3,5,7};
	vector<int>maxup={2,4,6,7},tmp;
	for(int i=0,j=0;i<ans.size() || j<maxup.size();){
		if(i<ans.size() && (j>=maxup.size() || ans[i]<=maxup[j])){
			tmp.push_back(ans[i]);
			i++;
		}else if(j<maxup.size() && (i>=ans.size() || ans[i]>maxup[j])){
			tmp.push_back(maxup[j]);
			j++;
		}
	}
	for(int i:tmp)cout << i << " ";*/
	cin >> n;
	for(int i=0;i<n;i++){
		int x;cin >> x;
		tar.push_back(x);
	}
	f=30+n/100+n/1000;
	srand(time(0));
	int w=1;
	while(ans.size()!=n){
		monkey_sort();
		//cout << endl << endl << endl;
		w++;
	}
	//cout <<endl;
	for(int i:ans)cout << i << " ";
	//cout << endl;
	//cout << w;
	/*random_shuffle(tar.begin(),tar.end());
	for(int i=0;i<n;i++){
		cout << tar[i] << " ";
	}*/
	return 0;
}
原文