简体   繁体   中英

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. Make sure you have initialized the ctr with 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");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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