在机房闲的没事干搞的。
Part I
众所周知,猴子排序算法是一种著名的排序算法,可以使用以下代码简单地实现一个测试猴子排序对于 个正整数的排序能力:
#include<bits/stdc++.h>
using namespace std;
#define int long long
int n=10,a[114514]={7,5,4,8,6,3,10,9,2,1};
signed main()
{
srand(time(0));
while(1)
{
for(int i=0;i<n;i++)
{
swap(a[i],a[rand()%n]);
}
bool flag=1;
for(int i=0;i<n-1;i++)
{
if(a[i]>a[i+1])
{
flag=0;
break;
}
}
if(flag)
{
break;
}
}
return 0;
}运行上述代码 次后,得到了如下结果(保留 位小数):
| 次序 | 时间(s) |
|---|---|
| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 平均值 |
结论:猴子排序算法对 个正整数进行排序时,虽然最快时间“较快”,但所用时间极不稳定,不建议在 OI 中使用。
Part II
同样的,我们也可以测试猴子排序对于 个正整数的排序能力,得到数据如下(保留 位小数):
| 次序 | 时间(s) |
|---|---|
| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 平均值 |
结论:猴子排序算法对 个正整数进行排序时,虽然最快时间仍在大部分题目的时间限制内,但平均时间极长,所用时间极不稳定,不建议在 OI 中使用。
Part III
使用以下代码,我们可以效率更高地测试猴子排序对 个正整数的排序效率:
#include<bits/stdc++.h>
#include<windows.h>
using namespace std;
#define int long long
int n=10,a[114514],cnt=0,tot=0,ave=0;
void reset()
{
for(int i=0;i<n;i++)
{
a[i]=i+1;
}
for(int i=0;i<n;i++)
{
swap(a[i],a[rand()%n]);
}
}
signed main()
{
srand(time(0));
reset();
int stime=GetTickCount(),etime;
while(1)
{
for(int i=0;i<n;i++)
{
swap(a[i],a[rand()%n]);
}
bool flag=1;
for(int i=0;i<n-1;i++)
{
if(a[i]>a[i+1])
{
flag=0;
break;
}
}
if(flag)
{
etime=GetTickCount();
tot+=etime-stime;
++cnt;
ave=tot/cnt;
if(cnt%10==0)
{
cout<<"已完成"<<cnt<<"次排序, 平均耗时"<<ave<<"ms\n";
}
reset();
stime=GetTickCount();
}
}
return 0;
}运行程序,当其完成排序 次时,观察到平均耗时为 毫秒。
结论:猴子排序算法对 个正整数进行排序时,平均用时较大,不建议在 OI 中使用。
Part IV
同样地,我们可以对 Part III 的代码稍作更改,使其能够测试猴子排序对 个正整数的排序效率。
运行程序,当其完成排序 次时,观察到平均耗时为 毫秒。
结论:不建议在 OI 中使用猴子排序算法(不想编了)。