我试图生成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;
}
我似乎无法弄清楚为什么这种情况不起作用。事实上,它只是反刍同一个名单。有人能指出我犯了什么错吗?
答案 0 :(得分:4)
交换代码不正确:此代码
temp = numb[d];
numb[d] = numb[d+1];
numb[d] = temp;
swapped = 1;
应该是
temp = numb[d];
numb[d] = numb[d+1];
numb[d+1] = temp;
swapped = 1;