当我输入值 1,2,3,4,5 时,我的代码没有显示第一遍,因为
- 计算我使用过的条件。 但我希望我的代码至少显示 1 遍(如果它也按排序顺序)。
- 如果您发现列表在任何中间点排序,请停止该过程。
这是我的代码:
#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++)
{
count=0;
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;
}
请帮助我,你们的建议和想法将非常感谢我。
最佳答案
你的代码没问题。为了确保打印每个 channel ,只需在循环开始时打印该 channel 即可。此外,您不需要声明额外的变量来跟踪传递。
for (i = 0; i < (s - 1); i++)
{
printf("\nAfter Pass %3d elements are: ", i);
for (j = 0; j < s; j++)
printf("%d ", a[j]);
count = 0;
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;
}
关于c - 修改后的冒泡排序不显示遍数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30528714/