Bula
Bula

Reputation: 2792

Why does Java jump after my return statement

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?

Upvotes: 3

Views: 450

Answers (2)

resueman
resueman

Reputation: 10613

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.

Upvotes: 9

Mureinik
Mureinik

Reputation: 311393

You are missing a return statement in the if branch. The call to partition just gets executed, its return value gets ignored, and then the function continues, and returns -1 after the if is terminated.

To fix it, just add a return call:

if(low < high){
    System.out.println("Somehow this point has been reached 2");
    //some more code
    return partition(array,low,high,pivot_index);
}

Upvotes: 0

Related Questions