"Binary Search"功能无法正常工作



当我运行代码并从用户处按升序输入数组时,我所做的函数运行,如果I从数组中搜索中间数字以找到它的位置,代码运行得很好。但是当我从数组中搜索不是中间的数字时,代码没有给我任何输出,请解决这个问题。

#include<iostream>
using namespace std;

void input_array(int arr[], int n);
int binary_search(int arr[], int n, int target);
int main()
{
int limit;
cout<<"Enter The Limit For An Array:- ";
cin>>limit;
int arr[limit];
input_array(arr, limit);
int target;
cout<<"Enter The Number to find its position:- ";
cin>>target;
binary_search(arr, limit, target);
}
void input_array(int arr[], int n)
{
cout<<"Enter The Number in Increasing Order "<<endl;
for (int i = 0; i < n; i++)
{
cout<<i+1<<". Enter Number :- ";
cin>>arr[i];
}   
}
int binary_search(int arr[], int n, int target)
{
int low = 0;
int high = n-1;
int mid;
for (int i = 0; i < n; i++)
{
mid = (low+high) / 2;
if (arr[mid] == target)
{
cout<<"The Position of The Given Target is :- "<<mid;
return 0;
}
if (arr[mid] > target)
{
low = mid + 1;
}

else
{
high = mid - 1;
}   
}
return -1;
}

我创建了一个不工作的程序,我不知道它不工作的原因,请解决我的问题,以便我可以继续。

试试这个:

while (low + 1 < high)
{
int mid = (low + high) / 2;
if (arr[mid] >= target)
low = mid;
else
high = mid;
}
if (arr[high] >= target)
return high;
if (arr[low] >= target)
return low;
return -1;

你只是循环N次,其中N是数组的大小,而对于二进制搜索,它最多循环log (N)次。除了一个简单的倒逻辑问题。下面我将向您展示如何修改这部分代码。

int binary_search(int arr[], int n, int target) {
int low = 0;
int high = n-1;
int mid;
while(low <= high) {
mid = (low+high) / 2;
if (arr[mid] == target) {
cout << "The Position of The Given Target is :- " << mid;
return 0;
}else if (arr[mid] < target) {
low = mid + 1;
} else {
high = mid - 1;
}   
}
return -1;
}
我希望我说得很清楚。不要担心询问更多信息

最新更新