整数变量存储 0 作为方法返回值

Kap*_*hab 2 java variables binary recursion search

我在 Java 中尝试二进制搜索递归程序,该算法似乎非常好,但是我存储递归函数结果的变量将 0 存储为值。在下面的代码中,我想存储在变量result 中找到的元素的索引,但是输出将result的值打印为 0。当我在 return 语句之前打印mid的值时,该值是正确的。这个问题怎么解决??

public class Main {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        int n;
        System.out.println("Enter the number of elements in the array: ");
        n = scanner.nextInt();

        int arr[] = new int[n];
        System.out.println("Enter the array elements (from index 0): ");
        for (int i = 0; i < n; i++) {
            arr[i] = scanner.nextInt();
        }

        int ele;
        System.out.println("Enter the element to be searched: ");
        ele = scanner.nextInt();
/*************************************************************************************/
        int result = binarySearchRecursive(arr, 0, n - 1, ele);
        System.out.println(result);
/************************************************************************************/

        if (result == -1) {
            System.out.println(ele + " not found");
        } else {
            System.out.println(ele + " found at index: " + result);
        }


    }

    //Algorithm

    public static int binarySearchRecursive(int arr[], int l, int r, int ele) {

        //Check whether a single element is present
        if (l == r) {
            if (arr[l] == ele) {
                return l;
            } else {
                return -1;
            }
        } else {      //Multiple elements
            int mid = (l + r) / 2;

            //Check conditions
            if (ele == arr[mid]) {
                System.out.println("Method return 'mid' value: "+mid);
                return mid;
            } else if (ele < arr[mid]) {
                binarySearchRecursive(arr, l, mid - 1, ele);
            } else {
                binarySearchRecursive(arr, mid + 1, r, ele);
            }

        }

        return -l;
    }

}
Run Code Online (Sandbox Code Playgroud)

这是输出

Era*_*ran 6

您应该返回递归调用的值:

        if (ele == arr[mid]) {
            System.out.println("Method return 'mid' value: "+mid);
            return mid;
        } else if (ele < arr[mid]) {
            return binarySearchRecursive(arr, l, mid - 1, ele);
        } else {
            return binarySearchRecursive(arr, mid + 1, r, ele);
        }
Run Code Online (Sandbox Code Playgroud)