I stumbled on some issue in my codes, supposedly a return will stop my method but in my case isn't. I tried to make a method called "binarySearch" which supposedly do what its made to do.
public int binarySearch(int lowIndex, int highIndex, int[] arr, int val) {
int middleIndex = (lowIndex + highIndex ) / 2;
if(arr[middleIndex] < val) {
lowIndex = middleIndex;
} else if (arr[middleIndex] > val) {
highIndex = middleIndex;
} else {
return middleIndex;
}
binarySearch(lowIndex, highIndex, arr, val);
return 0;
}
the problem is if I already found the index where the search value reside else statement will return it and stop already. but instead, I always get "0", which is I think the value i set for default return return 0. so for some clarification, I added some text on my else statement to make sure it executed and return middleIndex, then the text showed up so basically my loop enters else statement and hopefully returned middleIndex but its not. maybe recursion has to do with this but I don't know maybe you guys can help me.
binarySearch(lowIndex, highIndex, arr, val);binarySearchis calling itself with the same arguments that were passed to it. How is this ever producing anything other than an infinite loop and eventual stack overflow exception?lowIndex(if case) or thehighIndex(else if case) before calling itself