【问题标题】:counting comparisons in a binary search function计算二分查找函数中的比较
【发布时间】:2021-02-21 10:05:57
【问题描述】:

我正在运行这个二进制搜索功能,但我正在努力运行一个增量器来计算已进行的比较量。

我想在最后一个 cout 语句(为空)处输出比较次数。有人能指出我正确的方向吗?

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
  }
}

【问题讨论】:

  • edit 并用您正在使用的编程语言标记它,以便具有该语言经验的人更有可能找到它并为您提供帮助。
  • 看看你的代码,你认为在哪里进行比较?声明一个变量来计算比较。每次进行比较时,将变量加一。最后输出变量。好像没那么难,你在纠结什么?

标签: c++ arrays


【解决方案1】:
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
  }
}

注意:如果您不需要最终比较(找到的值),您可以从 -1 而不是 0 开始 comp。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-11-11
    • 2021-05-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-27
    • 2018-09-23
    • 2011-05-30
    相关资源
    最近更新 更多