public class BinarySearch {
//recursively searches through the sorted array to find 45
public static int binarySearch(int[] arr, int start, int end, int target) {
// find the middle index of the array
int mid = (start + end) / 2;
// middle element of the array is the target return index
if (arr[mid] == target) {
return mid;
}
// if the middle element is greater than the target, search the left half of the array
else if (arr[mid] > target) {
return binarySearch(arr, start, mid - 1, target);
}
// if the middle element is less than the target, search the right half of the array
else {
return binarySearch(arr, mid + 1, end, target);
}
}
//tester
public static void main(String[] args) {
int[] arr = {1, 3, 5, 7, 9, 23, 45, 67};
int target = 45;
int index = binarySearch(arr, 0, arr.length - 1, target);
System.out.println("Index of 45: " + index);
//should return index 6
}
}
BinarySearch.main(null);