|
10鱼币
请问大佬们,这代码是哪里有问题?
看似没问题每次随机都不一样,但是几分钟上百万次都随机不出正确答案。。。
顺带请教一下这种随机性代码怎么检查它有没有错过正确答案? #include<stdio.h>
#include<stdlib.h>
#include<time.h>
void bogo_sort(int*,int);
int main(void)
{
int array[] = {73, 108, 111, 118, 101, 70, 105, 104, 67};
int i, length;
time_t begin, end;
begin = time(NULL);
length = sizeof(array) / sizeof(array[0]);//length = 9;
bogo_sort(array, length);
printf("排序后的结果是:");
for (i = 0; i < length; i++)
{
printf("%d ", array[i]);
}
putchar('\n');
end = time(NULL);
printf("总共耗时:%ld秒\n", end - begin);
return 0;
}
void bogo_sort(int *array,int length)
{
int num1[length];//存放num2的下标
int num2[length];//储存array的随机排序
char ch;//判断数组是否排序成功
int i,j;
int count = 1;
srand((unsigned)time(NULL));
do{
for(i = 0;i < length;i++)
{
num1[i] = rand()%length;
for(j = 0;j < i;j++)
{
if(num1[j] == num1[i])
{
i--;
break;
}//保证下标不重复
}
}//随机生成num2的下标
printf("第%d次num2的下标为:",count ++);
for(i = 0;i < length;i ++)
{
printf("%d ",num1[i]);
}
putchar('\n');
for(i = 0;i < length;i ++)
{
num2[num1[i]] = array[i];
}//用num2存放随机排序的array数组
for(i = 0;i < length;i ++)
{
for(j = 0;j < i;j ++)
{
if(num2[j] > num2[i])
{
ch = 'N';
break;
}
ch = 'Y';
}//检查num是否从小到大排序,成功为Y,不成功为N
if(ch == 'N')
{
break;
}//没有正确排序直接进入下一次循环
}
printf("排序后的结果是:");
for(i = 0;i < length;i ++)
{
printf("%d ",num2[i]);
}
putchar('\n');
}while(ch == 'N');
for(i =0;i <length;i ++)
{
printf("我到了结尾!\n");
array[i] = num2[i];
}//将排序好的数组放入array
}
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
void bogo_sort(int*,int);
int main(void)
{
int array[] = {73, 108, 111, 118, 101, 70, 105, 104, 67};
//int array[] = {73, 108, 111};
int i, length;
time_t begin, end;
begin = time(NULL);
length = sizeof(array) / sizeof(array[0]);//length = 9;
bogo_sort(array, length);
printf("排序后的结果是:");
for (i = 0; i < length; i++)
{
printf("%d ", array[i]);
}
putchar('\n');
end = time(NULL);
printf("总共耗时:%ld秒\n", end - begin);
return 0;
}
void bogo_sort(int *array,int length)
{
int num1[length];//存放num2的下标
int num2[length];//储存array的随机排序
char ch;//判断数组是否排序成功
int i,j;
int count = 1;
srand((unsigned)time(NULL));
do{
for(i = 0;i < length;i++)
{
num1[i] = rand()%length;
for(j = 0;j < i;j++)
{
if(num1[j] == num1[i])
{
i--;
break;
}//保证下标不重复
}
}//随机生成num2的下标
printf("第%d次num2的下标为:",count ++);
for(i = 0;i < length;i ++)
{
printf("%d ",num1[i]);
}
putchar('\n');
for(i = 0;i < length;i ++)
{
num2[num1[i]] = array[i];
}//用num2存放随机排序的array数组
/*
for(i = 0;i < length;i ++)
{
for(j = 0;j < i;j ++)
{
if(num2[j] > num2[i])
{
ch = 'N';
break;
}
ch = 'Y';
}//检查num是否从小到大排序,成功为Y,不成功为N
if(ch == 'N')
{
break;
}//没有正确排序直接进入下一次循环
}
*/
ch = 'Y';
for(int i = 0; i < length - 1; ++i) {
if(num2[i] > num2[i + 1]) {
ch = 'N';
break;
}
}
printf("排序后的结果是:");
for(i = 0;i < length;i ++)
{
printf("%d ",num2[i]);
}
putchar('\n');
}while(ch == 'N');
for(i =0;i <length;i ++)
{
printf("我到了结尾!\n");
array[i] = num2[i];
}//将排序好的数组放入array
}
|
-
-
|