Not getting correct output in Bubble Sort question

Back to General discussions forum

shanbhag1996     2015-04-19 18:03:26

How do I calculate the number of passes? If I am right, the number of outer loops should be the number of passes but I an getting the wrong answer. Please help. Here is the code

#include <stdio.h>

int main()
{
    int t,i,j,swap,count=0,pass=0;
    scanf("%d",&t);
    int arr[t];
    for(i=0;i<t;i++)
    {
        scanf("%d",&arr[i]);
    }
    for(i=0;i<t-1;i++)
    {
        pass++;
        for(j=0;j<t-i-1;j++)
        {
            if(arr[j]>arr[j+1])
            {
                swap=arr[j];
                arr[j]=arr[j+1];
                arr[j+1]=swap;
                count++;
            }
        }
    }

    printf("%d %d",pass,count);
    return 0;
}
Quandray     2015-04-19 20:12:00
User avatar

I think you're counting the passes correctly.

What I don't think you're doing though, is stopping when a pass doesn't perform any swaps.

shanbhag1996     2015-04-19 23:56:57

Swapping happens in my inner j loop so how do I stop pass in outer loop when inner loop isn't working?

Quandray     2015-04-20 18:58:51
User avatar

Have a bool variable named DoneASwap
Before the inner loop, set DoneASwap to False
Inside the if, set DoneASwap to True
After the inner loop, if DoneASwap is False, break out of the outer loop

Please login and solve 5 problems to be able to post at forum