马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
猴子排序
为什么我这总是零秒就跑完了?虽然可以打印排序过程拖慢时间,是哪里除了问题?
#include <stdio.h>
#include <stdlib.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]);
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 i, j;
int temp, index;
_Bool flag;
srand(time(NULL));
do
{
for (i = 0; i < length; i++)
{
index = rand() % length;
temp = array[i];
array[i] = array[index];
array[index] = temp;
}
for (i = 0, flag = 1; i < length && flag; i++)
{
for (j = i+1; j < length && flag; j++)
{
flag = array[i] < array[j];
}
}
}while (!flag);
}
|