gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 23:46:25 24 4
gpt4 key购买 nike

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com