【发布时间】: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;
}
}
【问题讨论】:
-
请不要链接基本上只包含文字的图片,而是发布该文字。
标签: java variables recursion search binary