bogobogo sort(doge)蠢猴排序

众所周知,猴子排序是个非常看人品的排序,好的人一次完事,坏的人无限循环,谁都知道,打乱了再排,贴上代码

#include<bits/stdc++.h>
using namespace std;
int a[10000],n;
bool sorted(int n)
{
  while (--n>=1) 
    if(a[n]<a[n-1])
		return false;
  return true;
}
void bogosort(int n)
{
	while ( !sorted(n) )
  		for(int i=0; i<n; i++)
			swap(a[i],a[rand()%n]);
}
int main()
{
  scanf("%d",&n);
  for(int i=0;i<n;i++)scanf("%d",&a[i]);
  bogosort(n);
  for (int i=0; i < n; i++) printf("%d ", a[i]);
}

这是猴子排序,蠢猴排序是怎么运行的呢?比如:

一组平平无奇的样例

5 3 1 4 2

现在,有一个i指针指向下标为0的位置上(是5),5一个数是肯定排好序了

5 3 1 4 2

i指向的下标为1(是3)

接下来,把 5 3打乱,直到有序

3 5 1 4 2

i指向的下标为2(是1)

接下来,把 3 5 1打乱,直到有序

3 5 1 4 2

以此类推,直到全部有序

代码只要在bogo的基础上加一个for(int i=2;i<=n;i++)至于为什么从2开始,因为第一个数已经算是排好了(i代表到现在为止要排几个数)

贴上代码

#include<bits/stdc++.h>
using namespace std;
int a[100001],n;
bool is_sorted(int n)
{
  while ( --n >= 1 ) 
    if (a[n]<a[n-1])
		return false;
  return true;
}
void bogosort(int n)
{
	while ( !is_sorted(n) )
  		for(int i=0; i < n; i++)
			swap(a[i],a[rand()%n]);
}
int main()
{
  scanf("%d",&n);
  for(int i=0;i<n;i++)scanf("%d",&a[i]);
  for(int i=2;i<=n;i++)bogosort(i);
  for (int i=0; i < n; i++) printf("%d ", a[i]);
}

时间复杂度(最好): O(n^2)
时间复杂度(最坏): O(∞)
时间复杂度(平均): O(n*n!^n)(doge)

注:不要用于打代码,不然程序要挂的(az)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值