首先我给出我将输入多少个数字,然后我输入数字。他需要对它们进行冒泡排序,但其写法如下======> 1 3 2 6 = 0 0 0 0(但必须像1 2 3 6(从小到大))
我想要的应用程序=
7
1 5 2 7 4 7 3
1 2 3 4 5 7 7
#include<stdio.h>
int main()
{
int numbers[500000];
int counter=0;
int howmany;
scanf("%d",&howmany);//getting how many numbers will we enter
int howmany2=howmany;//we will use this for write all numbers after all
while(howmany>0)//getting all numbers
{
scanf("%d",&numbers[counter]);
howmany--;
counter++;
}
int checker1,checker2;//its gonna check first and second number, then second and third...etc
int hm=howmany-1;//its gonna check entered number-1 times(1,2,3)={1,2},{2,3}
int clone1;//later we will copy numbers[checker1]
int tentime=10;//we gonna do bubble sort 10 times
while(tentime>0)//doing bubble sort
{
checker1=0;
checker2=1;
while(hm>0)
{
if(numbers[checker1]>numbers[checker2])
{
clone1=numbers[checker1];
numbers[checker1]=numbers[checker2];
numbers[checker2]=clone1;
}
checker1++;
checker2++;
hm--;
}
tentime--;
}
int counter2=0;
while(howmany2>0)//showing new number sort on screen
{
printf("%d ",numbers[counter]);
howmany2--;
counter2++;
}
printf("\n");
return 0;
}
最佳答案
您的代码中有几个问题:
- 在第一个 while 循环结束时,有多少个将为 0。因此 hm 将被设置为 -1 并且排序循环(当 hm > 0 时)将永远不会运行。
- 当你打印结果时,使用 counter 作为数组索引(这是 4,它超出了范围,并且永远不会改变,因为你递增 counter2。因此,你打印出一个未定义的值(在你的例子中为 0)四次。
- 声明大小为 500000 的数组可能会炸毁您的堆栈。即使不是,它也比您需要的大得多
关于c - 我尝试用 C 进行冒泡排序,但它不起作用(它进行了 10 次冒泡排序),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58564966/