简体   繁体   English

二分查找比较计数器

[英]comparison counter on binary search

So, I have a binary search code (not mine) and I don't know how to put a counter on how many comparisons it made.所以,我有一个二进制搜索代码(不是我的),但我不知道如何将计数器放在它进行了多少次比较上。 The elements are entered then sorted.输入元素然后排序。 Then this codes comes after.然后这个代码来了。

    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");

You can increment count like this:您可以像这样增加计数:

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

  middle = (first + last)/2;
}
System.out.println("Counter = " + count);

Simply increment the value of ctr for all the three cases.只需为所有三种情况增加ctr的值。 Make sure you have initialized the ctr with 0 ;确保您已使用0初始化ctr

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");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM