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

标签 java variables recursion search binary

我在 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;
    }

}

Here is the output

最佳答案

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

        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);
        }

关于java - 整数变量存储 0 作为方法返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64114413/

相关文章:

bash - 查找进程的所有祖先和子进程

Java 二叉树插入无法正常工作

java - 使用 removeContent() 从 JDOM 文档中删除元素

java - 在 Java 中,如何创建线程以便每个线程都专门运行在一个内核中?

java - 获取java.security.InvalidKeyException : Key must be 128, 192或256位长twofish

java - 将用户输入中的多个变量放入数组列表中

javascript 全局变量 UNSET

variables - 为什么 perl6 不能自动激活,这样我就不必一直使用 "my"?

list - Ocaml 从递归函数返回列表

java - 我的java程序时不时地卡住并且可能存在内存泄漏。我的遥测有用吗?