C中的冒泡排序不排序
Bubble sort in C not sorting
我正在尝试生成 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;
}
我似乎无法弄清楚为什么这种方法不起作用。事实上,它只是重复相同的列表。有人可以指出我在哪里犯了错误吗?
您的交换代码不正确:此代码
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;
我正在尝试生成 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;
}
我似乎无法弄清楚为什么这种方法不起作用。事实上,它只是重复相同的列表。有人可以指出我在哪里犯了错误吗?
您的交换代码不正确:此代码
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;