icysnow
icysnow

Reputation: 9

May I know why the counter is 1 and 4 for this code?

I am given sort(a,4),sort(a,6) in this question.

Starting with sort(a,4)
npts =4 which mean I need to loop from 0 ~ 2
1st loop x[] = { 5,7,3,1,6,9}
2nd loop x[] = {5,3,7,1,6,9}
3rd loop x[] = {5,3,1,7,6,9}
exit the loop
counter =1;
back into the for loop
1st loop x[] = {3,5,1,7,6,9}
2nd loop x[] = {3,1,5,7,6,9}
exit loop the loop
counter =2;
back into the for loop
1st loop x[] = {1,3,5,7,6,9}
exit the loop
counter =3;
back into the for loop
but exit immediately since 1>3 
counter = 4;

Then going to the sort(a,6);
counter =1 since 1>3;

But the answer is opposite when I compile using mingw which is 1 4

My code is as followed:

#include <stdio.h>
int sort (int x[],int npts);
int main(void)
{       
   int a[] = {7,5,3,1,6,9};
    printf("%d %d\n",sort(a,4),sort(a,6)); 
       return 0;
    }
    int sort(int x[] , int npts)
    {
       int counter =0, done, hold ,k;

       do
        {

          done =1;
          for(k=0;k<=npts-2;k++)
          {
             if (x[k] > x[k+1])
             {       

                hold= x[k];
                x[k] = x[k+1];
                x[k+1] = hold;
                done =0;  
              }
          }
          counter++;
        }while (!done);
        return counter;
    }

Upvotes: 0

Views: 54

Answers (1)

P.P
P.P

Reputation: 121407

 Starting with sort(a,4) npts =4 ...

No. It doesn't have to be. You seem to be expecting sort(a,4) called first and then sort,6). The order of evaluation of arguments to printf() function is unspecified. That means, you don't know which one of sort(1,4 and sort(a,6) will be called first.

Calling them one after another would give predictable result.

Upvotes: 5

Related Questions