c - 修改后的冒泡排序不显示遍数

标签 c sorting bubble-sort

当我输入值 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/

相关文章:

c - 有没有办法以编程方式将名称解析限制为/etc/hosts 中存在的条目?

c - Visual Studio 2017 跨平台中特定于 Linux 的 header

java - 按映射值对字符串列表进行排序

java - 冒泡排序不对单个元素进行排序

c++ - 试图了解我的冒泡排序方法有什么问题

c - 带字符串的结构数组

c - 不懂C程序

java - 对以 map 作为输入的列表进行排序

c++ - 对二维结构数组进行排序

algorithm - 冒泡排序算法分析