如何在C++中为二进制搜索设置计数器

How to have a counter for a binary search in C++?

本文关键字:二进制 搜索 设置 计数器 C++      更新时间:2023-10-16

我不知道如何为二进制搜索设置计数器,以确定在找到输入的目标数字之前进行了多少比较。我是否在二进制搜索的末尾添加一个计数器?

void search (int arr[])
{
int target;
int first = 0,
    last = MAX - 1,
    mid,
    position = -1;
int row = 2;
    bool found = false;
cout << "Enter in target number to search for: ";
cin >> target;
while (!found && first <= last)
{
    mid = (first + last) / 2;
    if (avg[row][mid] == target)
    {
        cout << "found at index " << mid << endl;
        found = true;
    }
    else if (avg[row][mid] > target)
        last = mid - 1;
    else
        first = mid + 1;
}
if (!found)
    cout << "Not foundn";
}
int counter = 0;                  // Number of comparisons before target is found
while (!found && first <= last)
{
    mid = (first + last) / 2;
    counter = counter + 1;        // Changes to be made
    ... Rest of the code
    else
        first = mid + 1;
}

int counter = 0;                  // Number of comparison before target is found
while (!found && first <= last)
{
    mid = (first + last) / 2;
    if (avg[row][mid] == target)
    {
        cout << "found at index " << mid << endl;
        found = true;
        counter = counter + 1;
    }
    else if (avg[row][mid] > target) 
    {
        last = mid - 1;
        counter = counter + 1;      // Changes to be made
    }
    else 
    {
        first = mid + 1;
        counter = counter + 1;      // Changes to be made
    }    
}

这里,计数器在while循环之前声明,然后每次递增一,直到找到结果。

我会在while循环之前定义一个计数器变量,并在while环路结束时,在最后一个else(不在else子句中)

之后递增

int计数=0;…代码的其余部分否则if(avg[row][mid]>目标)last=mid-1;计数++

else
    first = mid + 1;
    count++;

}if(!已找到)cout<lt;"未找到\n";cout<lt;"counter="<