我在这个问题上给出了排序(a,4),排序(a,6)。
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
我的代码如下:
#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;
}
答案 0 :(得分:5)
Starting with sort(a,4) npts =4 ...
没有。它不是必须的。您似乎期望首先调用sort(a,4)
然后调用sort,6)
。 printf()函数的参数的评估顺序是未指定。这意味着,您不知道将首先调用sort(1,4
和sort(a,6)
中的哪一个。
一个接一个地调用它们会产生可预测的结果。