I'm trying to do a recursive binary search on an ArrayList but not sure what the issue with my code is. I have a text file with a bunch of integer numbers that look like this:
217 320 550 212 12 17 3560 2999 211
The problem is that when I input a number to search the ArrayList, it always says the element does not exist, but I know it does!
public static int binarySearch(List<Integer> arr, Integer l, Integer r, Integer x)
{
if (r>=l)
{
Integer mid = l + (r - l)/2;
// If the element is present at the middle itself
if ((arr.size()/2) == x)
return mid;
// If element is smaller than mid, then it can only
// be present in left subarray
if ((arr.size()/2) > x)
return binarySearch(arr, l, mid-1, x);
// Else the element can only be present in right
// subarray
return binarySearch(arr, mid+1, r, x);
}
// We reach here when element is not present in array
return -1;
}
}
Any help would be greatly appreciated, new programmer here!