下面的代码用于对排序后的数组执行二进制搜索,然后返回查找用户输入值所需的比较次数。
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语句“找不到值”。进行试用,但即使这样也无法正常工作。如果我运行代码,这就是我得到的结果
下面的代码用于对排序后的数组执行二进制搜索,然后返回查找用户输入值所需的比较次数。 int binarySearch(int arr [],int numelems,int value){...
您可以在返回之前简单地添加if
语句,例如: