-
return in recursion
The following code is a simple recursive binary search method that is supposed to return the index of the first match in an array, or -1 while no match. The test case result shows that no matter what if-then case it jumps to, it returns only 0, which I think, is from the very last statement. But, that statement can't be removed, otherwise "no return" error occurs. Would anyone help figure this out? Thanks
public int findLocation(int[] anArray, int aTarget, int lowIndex, int highIndex){
if(lowIndex>highIndex){
System.out.println("can't find it!");
return -1;
}
Mid=(int) (lowIndex+highIndex)/2;
if(anArray[Mid]==aTarget){
System.out.println("There is a match!");
return Mid;
}
if(anArray[Mid]<aTarget){
lowIndex=Mid+1;
findLocation(anArray, aTarget, lowIndex, highIndex);
}
else if(anArray[Mid]>aTarget){
highIndex=Mid-1;
findLocation(anArray, aTarget, lowIndex, highIndex);
}
return 0;
-
This is not "advanced java", but more importantly it is a double post which is not fair to the volunteers of this forum as it needlessly splits the discussion. Locking this thread and deleting soon. OP, please no more double posting questions.