简体   繁体   中英

counting comparisons in a binary search function

I'm running this binary search function and I'm struggling to run an incrementer that counts the amount of comparisons that have been made.

I'd like for the number of comparisons to output at the last cout statement (which is empty). Can someone point me in the right direction?

void binarySearch( int nums[], int size)
{
  int first = 0;       //first array elements
  int last = size - 1; //last array
  int middle;          //midpoint of search
  int position = -1;   //position of search value
  bool found = false;  //flag

  for (int j = 1; j < 4; j++)
  {
    int randVal = rand() % size + 1; //rand value to be searched
    
    while (!found && first <= last)
    {
     middle = (first + last) / 2; //calculate midpoint
     if( nums[middle] == randVal) //if value is at mid
      {
        found = true;
        position = middle;
      }
      else if (nums[middle] > randVal) //if value is in lower half
      { last = middle - 1; }
     else
      { first = middle + 1; } //if value is in upper ha;f
    }
  cout << "|Run " << j << ": " << endl;
  cout << " -Search: " << randVal << "\n"; //cout searched value
  cout << " -Comparisons: " << "\n\n"; //cout # of comparisons that were made
  }
}
void binarySearch( int nums[], int size)
{
  int first = 0;       //first array elements
  int last = size - 1; //last array
  int middle;          //midpoint of search
  int position = -1;   //position of search value
  bool found = false;  //flag
  

  for (int j = 1; j < 4; j++)
  {
    int comp = 0;
    int randVal = rand() % size + 1; //rand value to be searched
    
    while (!found && first <= last)
    {
      comp++;
     middle = (first + last) / 2; //calculate midpoint
     if( nums[middle] == randVal) //if value is at mid
      {
        found = true;
        position = middle;
      }
      else if (nums[middle] > randVal) //if value is in lower half
      { last = middle - 1; }
     else
      { first = middle + 1; } //if value is in upper ha;f
    }
  cout << "|Run " << j << ": " << endl;
  cout << " -Search: " << randVal << "\n"; //cout searched value
  cout << " -Comparisons: " << comp << "\n\n"; //cout # of comparisons that were made
  }
}

NB: If you dont need the final comparison (value found) you can start comp at -1 instead of 0.

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