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

问题描述 投票:0回答:1

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

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”时得到的结果。 (结果正确)。

enter image description here

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

因此,理想情况下,如果我尝试搜索数字“ 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语句“找不到值”。进行试用,但即使这样也无法正常工作。如果我运行代码,这就是我得到的结果

enter image description here

下面的代码用于对排序后的数组执行二进制搜索,然后返回查找用户输入值所需的比较次数。 int binarySearch(int arr [],int numelems,int value){...

c++ binary-search
1个回答
0
投票

您可以在返回之前简单地添加if语句,例如:

© www.soinside.com 2019 - 2024. All rights reserved.