I've written binary search with only my own efforts 💪💪 without glancing at anywhere. I stuck on finding base case. At final, I think that if last checking is less than first index or first checking is greater than last index, it stops. But, I'm still suspicious of its performance and righness. I could return Integer.MAX_VALUE
or Integer.MIN_VALUE
if the searched number is not in the array but I assumed that all numbers are positive.
In the beginning times of writing recursion, I had difficulty in thinking recursively. But, now I have difficulty in finding base case(s).
public static int binarySearch(int[] arr, int key, int low, int high) {
if (high < 0 || low > high )
return -1;
int middleIndex = (low + high) / 2;
if (arr[middleIndex] == key)
return middleIndex;
else if (key > arr[middleIndex])
return binarySearch(arr, key, middleIndex + 1, high);
else
return binarySearch(arr, key, low, middleIndex - 1);
}
int arr[]
has to be sorted ;) \$\endgroup\$