【发布时间】:2017-10-21 04:26:20
【问题描述】:
我正在尝试生成 10 个随机数并对它们进行排序。但他们没有得到排序。
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
main()
{
int c, d, swapped, temp;
int numb[10];
time_t t;
srand(time(&t));
for (c=0; c<10; c++)
{
numb[c] = (rand() % 100) + 1;
}
printf("Before sorting:");
for (c=0; c<10; c++){
printf("%d\n", numb[c]);
}
for (c=0; c<10; c++)
{
swapped = 0;
for (d=0; d < 9 - c; d++)
{
if (numb[d] > numb[d+1])
{
temp = numb[d];
numb[d] = numb[d+1];
numb[d] = temp;
swapped = 1;
}
}
if (swapped == 0)
{
break;
}
}
printf("\nAfter sorting:\n");
for (c=0; c<10; c++)
{
printf("%d\n", numb[c]);
}
return 0;
}
我似乎无法弄清楚为什么这种方法不起作用。事实上,它只是重复了同一个列表。有人可以指出我在哪里犯了错误吗?
【问题讨论】:
-
srand(time(&t));->srand(time(NULL));- 然后你可以删除time_t t; -
你能解释一下有什么区别吗?
-
只需保存一个不需要的变量。
标签: c sorting bubble-sort