如何计算在 FOR 循环中检查条件的次数

How to calculate number of times a condition is checked in FOR loop

我正在编写一个插入排序程序。

我想知道 for 循环中的 "condition i.e a[k]>temp" 检查了多少时间以确定完成的比较次数。

如何找到它?

    int i,j,k,moves=0,comparison=0;
    for(j=1;j<arr_length;j++)
        {
            temp=a[j];
            for(k=j-1;k>=0 && a[k]>temp;k--)
             {
                 moves+=1;
                 a[k+1]=a[k];
                 a[k]=temp;
             }
        }

        printf("No. of Moves%d",moves);
        printf("Comparisons%d",comparison);

我会将比较 'a[k] > temp' 放入一个递增计数器的函数中。

bool check( int &counter, int lhs, int rhs )
{
    ++counter;
    return lhs > rhs;
}

...

int counter = 0;

...

for (k=j-1;k>=0 && check( counter, a[k], temp );k--)

获得正确值的最简单方法是在逗号分隔列表中使用附加变量:

size_t count= 0;

for(k=j-1;k>=0 && ( count++ , a[k]>temp ) ; k--)

这将评估 count++a[k]>temp,但比较中使用的值将仅为 a[k]>temp

您已经 k。用它。

for()循环后,如果k>= 0,则k的初始值减去k的当前值[这里j-1] .这将为您提供 a[k]>temp [for() 循环条件检查] 已执行的次数。

首先,所有问题的根源都是晦涩的循环。首先将您的程序修改为更具可读性的内容,其中 3 个循环语句保持简单。此外,始终从 0 开始计数,否则您会一遍又一遍地陷入数组索引错误。

  int moves = 0;
  int comparisons = 0;

  for(int j=0; j<arr_length; j++)
  {
    temp = a[j+1];

    for(int k=j; k>=0; k--)
    {
      comparisons++;
      if(a[k] <= temp)
      {
        break;
      }

      moves++;
      a[k+1]=a[k];
      a[k]=temp;
    }
  }

清理代码而不是进一步混淆它始终是明智的做法。