二进制搜索中的比较计数器

时间:2018-10-28 03:01:57

标签: java binary-search

因此,我有一个二进制搜索代码(不是我的),并且我不知道如何对它进行的比较次数计数。 输入元素然后进行排序。 然后出现此代码。

    System.out.println("\nEnter value to find");
    num_search = in.nextInt();

    first  = 0;
    last   = n - 1;
    middle = (first + last)/2; 

    while( first <= last )
    { 
      if ( a[middle] < num_search )
        first = middle + 1;    
      else if ( a[middle] == num_search )
     {
       System.out.println(num_search + " found at location " + (middle + 1) + ".");
          System.out.println("Counter = " + (ctr + middle));
        break;
      }
      else
     last = middle - 1;

      middle = (first + last)/2;
    }
    if (first > last)
  System.out.println(num_search + " isn't present in the list.\n");

2 个答案:

答案 0 :(得分:0)

您可以像这样增加计数:

?cbind

答案 1 :(得分:0)

对于所有三种情况,只需增加ctr的值即可。 确保已使用ctr初始化0;

while( first <= last )
    { 
      if ( a[middle] < num_search )
        {first = middle + 1;
        ctr++; //<----increment the count by 1
        }
      else if ( a[middle] == num_search )
     {
       ctr++; //<----increment the count by 1
       System.out.println(num_search + " found at location " + (middle + 1) + ".");
       System.out.println("Counter = " + ctr); //<-----add 1 to result
       break;
      }
      else
      {last = middle - 1;
      ctr++; //<----increment the count by 1
      }

      middle = (first + last)/2;
    }
    if (first > last)
        System.out.println(num_search + " isn't present in the list.\n");