二进制搜索功能-即使在数组中找不到数字,也输出比较的次数

Binary Search Function- Output the number of compares even the number cannot be found in the array

下面的代码用于对排序数组执行二进制搜索,然后 return 查找用户输入值需要进行多少次比较。

int binarySearch(int arr[], int numelems, int value)
    {
        int first = 0, last = numelems - 1, middle, position = -1;
        bool found = false;
        int count = 0;
        while (!found && first <= last)
        {

            middle = (first + last) / 2;
            if (arr[middle] == value)
            {
                found = true;
                position = middle;
                count++;
            }
            else if (arr[middle] > value)
            {
                last = middle - 1;
                count++;
            }
            else
            {
                first = middle + 1;
                count++;
            }
        }
        return count;
    }

下面是我调用函数搜索数字“38”时得到的结果。 (结果正确)。

我正在尝试编辑此函数,以便即使数组中不存在用户输入的数字,它也可以打印出比较次数。

所以,理想情况下,如果我尝试搜索数字“24”,程序应该打印出如下内容:

The value 24 does not exist in the array.
It took 5 compares to reach the conclusion. 

不知怎么的,我不太明白该怎么做... 我试图在 while 循环之外添加一个 if 语句,如下所示

int binarySearch(int arr[], int numelems, int value)
{
    int first = 0, last = numelems - 1, middle, position = -1;
    bool found = false;
    int count = 0;
    while (!found && first <= last)
    {
        middle = (first + last) / 2;
        if (arr[middle] == value)
        {
            found = true;
            position = middle;
            count++;
        }
        else if (arr[middle] > value)
        {
            last = middle - 1;
            count++;
        }
        else if (arr[middle] < value)
        {
            first = middle + 1;
            count++;
        }
    }
    if (found = false)
    {
        cout << "Value not found.";
    }
    return count;
}

即使程序没有找到数字,我也不确定如何打印出计数,所以我简单地写了一个 cout 语句 "Value not found." 来试用,但即使那样也行不通。如果我 运行 代码,这就是我得到的结果

您可以在 return 之前简单地添加一个 if 语句,例如:

    if (!found)
    {
        cout << "The value " << value << " not found.\n";
    }

或者您可以 return 两个带有 std::pair 的值(无论是否找到值和计数)。基于此,您可以在调用站点打印结果。