Search code examples
csortingbubble-sort

modified bubble sort not showing the passes


My code is not showing the first pass when I entered the value 1,2,3,4,5 because of the

  • count condition which i have used. But i want my code to show at least 1 pass if it is in sorted order also.
  • stop the process if u find that the list is sorted in any intermediate point.

Here is my code:

#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;
}

Help me out guys,Your suggestion and idea would be very thankful to me.


Solution

  • Your code is fine. To make sure every pass is printed then simply print the pass at the start of the loop. Also you don't need to declare additional variables to keep track of pass.

    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;
    }