首页 > 解决方案 > If my recursive method return true, why it enters a recursive call?

问题描述

im working with multi-dim arrays. i wrote a method that uses binary search to see if some int is in one the sub arrays. i debugged the binarySearch it works fine. i debugged the method that calls binarySearch. i saw that it entered the if statment. returned true. but it enters once again into the recursive call.

my code:

int[][] mainArr = {
            {1,1,1,1},
            {1,2,3,4},
            {4,5,6,6},
            {6,7,8,9}
    };
    System.out.println(exerciseSix(mainArr, 5, 0));

}

public static boolean exerciseSix(int[][] arr, int x, int position){
    int binAns = -1;
    if(position == arr.length){
        return false;
    }
    if(x == arr[position][arr[position].length - 1]){
        return true;
    }

    if(x < arr[position][arr[position].length - 1]){
        binAns = binarySearch(arr[position], 0, arr[position].length, x);
    }
    if(x == binAns){
        return true;
    }
    if(x > arr[position][arr[position].length - 1]){
        exerciseSix(arr, x, ++position);
    }
    return false;
}

static int binarySearch(int[] arr, int l, int r, int x){//l is the left most index
    if(r < l)
        return -1;
    int m = l+(r-l)/2;
    if(arr[m] == x)
        return arr[m];
    if(arr[m] < x)
        return binarySearch(arr, m+1, r, x);
    return binarySearch(arr, l, m-1, x);
}

标签: javarecursion

解决方案


Could it be that you are not using the value returned? eg in this part:

if(x > arr[position][arr[position].length - 1]){
    exerciseSix(arr, x, ++position);
}
return false;

No matter what exerciseSix(arr, x, ++position) returns it will be thrown away and it hits the next line which is return false. Earlier in a similar situation you assign the result to a variable, but here you downright discard it making it dead code. If you wanted to return it you need to write return exerciseSix(arr, x, ++position); since return only works on level at a time.


推荐阅读