Ok I’m really confused about something about recursion in Java. Say I have the following code:
static int findShortestString(String[] paths, int lo, int hi) {
if(lo==hi)
return lo;
int minindex=findShortestString(paths,lo+1, hi);
if(safeStringLength(paths[lo])<safeStringLength(paths[minindex]))
return lo;
return minindex;
Now the question is not really about the code itself, but just about how recursion works. minindex is being set equal to a recursive call. So the first time the function run and tries to set minindex to something, it does so, and then the function calls itself. But when does the if statement run then? Will it only run when minindex finally actually holds a real value? I just cant wrap my head around this. If minindex causes the function to recurse and recurse, then when will the if statement ever be checked? When lo==hi? I dont get it:(
minindexis not assigned untilfindShortestStringreturns, which won’t happen untillo == hi.Each time the method calls itself, it narrows the difference between
loandhiby 1, so eventually they’ll be equal* and that value will be returned.An example, with
paths = ["p1", "path2", "longpath3"]:lo = 0, hi = 2 lo != hi -> call findShortestString(paths, 1, 2) lo = 1, hi = 2 lo != hi -> call findShortestString(paths, 2, 2) lo = 2, hi = 2 lo == hi -> return lo (=2) lo = 1, hi = 2, minindex = 2 length of "path2" < length of "longpath3" -> return lo (= 1) lo = 0, hi = 2, minindex = 1 length of "p1" < length of "path2" -> return lo (= 0)I’ve tried to illustrate the variable values at each level of recursion using increasing amounts of indentation. At the beginning of each recursive call, the previous values of
lo,hiandminindexare saved off (in a structure called a “stack”) and the new values used instead. When each invocation of the method returns, the previously saved values are “popped” off the stack for use, andminindexassigned from the previous return value.*unless lo > hi to begin with, I guess…