簡體   English   中英

二分查找比較計數器

[英]comparison counter on 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");

您可以像這樣增加計數:

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

只需為所有三種情況增加ctr的值。 確保您已使用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