【问题标题】:Integer variable stores 0 as method return value整数变量存储 0 作为方法返回值
【发布时间】:2021-01-14 18:11:54
【问题描述】:

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

【问题讨论】:

  • 请不要链接基本上只包含文字的图片,而是发布该文字。

标签: java variables recursion search binary


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    您必须在 binarySearchRecursive 的递归函数调用中添加返回语句。现在你的代码总是落到最后一个返回语句,它只返回 -l => 它为 binarySearchRecursive(arr, 0, n - 1, ele); 返回 0;

        return binarySearchRecursive(arr, l, mid - 1, ele);
    
        return binarySearchRecursive(arr, mid + 1, r, ele);
    

    【讨论】:

      猜你喜欢
      • 2020-08-15
      • 2015-11-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-17
      • 2015-05-01
      • 2013-09-03
      相关资源
      最近更新 更多