bool binsearch(string phrase, vector<string> words, int from, int to, int &test)
{
while (tf == "y") //tf is a global variable
{
int mid = (to+from)/2;
if (words[mid] == phrase) {tf = "t"; return true;}
if (mid == test) {tf = "f"; return false;}
if (words[mid] > phrase) {return binsearch(phrase, words, mid-1, to, mid);}
else {return binsearch(phrase, words, from, mid+1, mid);}
}
}
i’m working on getting this binary search working. i need the overall function to return either “true” or “false”. i understand how the recursion works up until either line 6 or 7 executes and the return command is invoked. i’ve done research, and it seems like there’s no way to exit the function right there and it has to “unwind” itself. the tf global variable nonsense is so it won’t execute that body again when it’s unwinding…but i’m still not getting the results i want.
essentially, i just want to get out of the function ASAP after either the return true or return false command is invoked, and return the value to the main function accordingly
Thanks
I don’t understand your binary search either, and using global variables in addition to recursion leads to programs which are very hard to understand. It’s better to go back the call stack again and “unwind” it properly. Look at the following example (untested):