[英]Function for "Binary Search" does not work correctly
When I Run my code And take input of array in ascending order from user the function which i have made runs and if the i search the middle number from array to find its location the code runs perfectly fine.当我运行我的代码并从我运行的用户 function 中按升序获取数组输入时,如果我从数组中搜索中间数字以找到它的位置,代码运行得非常好。 But when i search the number from array which is not middle the code does not give me any output please fix this issue.
但是当我从不在中间的数组中搜索数字时,代码没有给我任何 output 请解决这个问题。
#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;
}
i have created a program which is not working i dont know the reason why its not working kindly please solve my issue so i can proceed further.我创建了一个无法正常工作的程序,我不知道它无法正常工作的原因,请解决我的问题,以便我可以继续进行。
Try this instead:试试这个:
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;
You were simply cycling N times, where N is the size of the array while with binary search it cycles at most log (N) times.您只是循环 N 次,其中 N 是数组的大小,而使用二进制搜索它最多循环 log (N) 次。 In addition to a trivial problem of inverted logic.
除了一个微不足道的反逻辑问题。 Below I show you the part of the code how it should be modified.
下面我将向您展示代码的一部分应该如何修改。
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;
}
I hope I was clear.我希望我说得很清楚。 Don't worry about asking for more information
不要担心询问更多信息
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.