I'm trying to build a recursive function as follows:
private static int partition(int[] array, int low, int high, int pivot_index){
// just irrelevant code
System.out.println("Somehow this point has been reached 1");
if(low < high){
System.out.println("Somehow this point has been reached 2");
//some more code
partition(array,low,high,pivot_index);
}else{
System.out.println("Somehow this point has been reached 3");
//some more code
return high;
}
System.out.println("Somehow this point has been reached 0");
return -1;
}//partition
What startles me is that after running my program and calling this function the compiler prints:
point 1 reached; point 2 reached; point 1 reached; point 3 reached. point 0 reached.
Which returns the -1 that crashes the entire logic of the program. I am sure I'm missing something here but how does my program jump after the if-else statement. There is no, to my knowledge, case where that if-statement doesn't get executed?
If the if condition is true, then it doesn't return immediately. After calling partition, it will exit the if statement, and continue to the end.
If you want the value calculated by the recursion to be returned, you need to change it to
if(low < high){
System.out.println("Somehow this point has been reached 2");
//some more code
return partition(array,low,high,pivot_index);
}
Right now, it's just discarding the results of the recursion, and returning the failure value. You need to explicitly say that you want to return that value.
So imagine that you pass in data that will be recursively called one time. The first call will enter the if block, and make the recursive call. The second call will enter the else block, and return high. This passes control back to the initial call, which discards the results of the second call, exits the if statement, and returns -1.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With