I was trying Binary Search recursive program in Java, the algorithm seems to be perfectly fine, but the variable in which I store the result from the recursive function, is storing 0 as the value. In the following code, I want to store the index of the element found in the variable result, but the output prints result's value as 0. When I print the value of mid before the return statement, the value is correct. How to fix this problem??
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;
}
}