Reputation: 123
I wrote a recursion program for binary search as you see I am trying to find the position of the target =21 in the given array which sohould return me position as 2. However my output is 1. While I debug the it matches att arr[start]=target, However it straight was jumps to the line findTheNumber(arr, mid + 1, end, target); then next line and then return mid.. Just wondering why my return is breaking off at the "return start"
package Recursion;
public class BinarySearch {
static int mid = 0;
public static int findTheNumber(int[] arr, int start, int end, int target) {
if (arr[start] == target) {
return start;
}
mid = (start + end) / 2;
if (arr[mid] == target) {
return mid;
}
if (target >arr[mid]) {
findTheNumber(arr, mid + 1, end, target);
} else if (target <arr[mid]) {
findTheNumber(arr, start, mid-1, target);
}
return mid;
}
public static void main(String[] args) {
int[] arr = { 10, 12,21 };
int start = 0;
int end = arr.length - 1;
int target = 21;
System.out.println(findTheNumber(arr, start, end, target));
}
}
Upvotes: 1
Views: 152
Reputation: 1524
if (target >arr[mid]) {
findTheNumber(arr, mid + 1, end, target);
} else if (target <arr[mid]) {
findTheNumber(arr, start, mid-1, target);
}
You're just returning your mid
point there, not the actual result of the recursive call.
Your code should look like:
if (target >arr[mid]) {
return findTheNumber(arr, mid + 1, end, target);
} else if (target <arr[mid]) {
return findTheNumber(arr, start, mid-1, target);
}
Upvotes: 5