Back to General discussions forum
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;
}
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.
Swapping happens in my inner j
loop so how do I stop pass in outer loop when inner loop isn't working?
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