编写一个 C 程序对 n 个元素的数组执行冒泡排序。
注意:如果你发现列表在任何中间点排序,请停止进程
它适用于其他数字,但当我输入 3、2、4、5、6 时,它没有正确显示传球次数。它没有正确显示传球次数,而是为每次传球重复相同的值。
输入元素个数:
5
输入元素1
3
输入元素2
2
输入元素3
4
输入元素4
5
输入元素5
6
未排序的列表是:
3 2 4 5 6
第一遍之后的元素是:2 3 4 5 6
在 Pass 2 之后元素是:2 3 4 5 6
在 Pass 3 之后元素是:2 3 4 5 6
在 Pass 4 之后元素是:2 3 4 5 6
排序列表是:
2 3 4 5 6
请帮我解决这个问题。
这是我的代码:
#include<stdio.h>
int main(){
int s,i,j,temp,a[20],count=0,x,n=0;
printf("Enter the number of elements :\n");
scanf("%d",&s);
for(i=0;i<s;i++)
{
printf("Enter element %d\n",i+1);
scanf("%d",&a[i]);
}
printf("Unsorted list is :\n");
for(i=0;i<s;i++)
{
printf("%d ",a[i]);
}
for(i=0;i<(s-1);i++)
{
n++;
for(j=0;j<(s-i)-1;j++)
{
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
count++;
}
}
if(count<0)
{
break;
}
else
{
printf("\nAfter Pass %d elements are :",n);
for(x=0;x<s;x++)
{
printf("%d ",a[x]);
}
}
}
printf("\nSorted list is :\n");
for(i=0;i<s;i++)
printf("%d ",a[i]);
return 0;
}
最佳答案
您需要在循环开始时将计数重置为 0。当你交换元素时,它会增加,但你永远不会绊倒 if (count <= 0)
除非您只计算此通行证的掉期数。
关于c - 修改后的冒泡排序通过错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30518179/