Binary Search Boolean Function

Hello Programmers, I am new to the forum and I am in need of some guidance on the logic of the following function. The desired outcome is to return a Boolean flag of false when the search does not return an index, if an index is found then the function should return the position of the found index. The problem with this code is that it only returns “False”. I have line traced the code and my logic and I am not able to identify the problem. Please guide me to a solution.


Here is the function:
bool binary_search2(vector<int> v, int from, int to, int value, int& m){
static bool flag=false;
int mid=(from+to)/2;
if(from<=to)
{
if(value<v[mid])
binary_search2(v, value, from,mid-1,m);
else if(value>v[mid])
binary_search2(v, value, mid+1,to, m);
else flag=true;
}
return flag;
}

Thank You!
Last edited on
This static bool flag=false; makes no sense since any recursion modifies it. Instead remove the static and use the result of the recusive call
Thanks for your help coder777. Big time rookie mistake to set the flag as static. I have modified the code and the code continues to return false for any values within the vector eventhough the search values are found within the vector. What other suggestions do you have?
Thank you!
Topic archived. No new replies allowed.