Below is the completed code that can for the binarySearch method, and it is made up of counting the number of calls to binarySearch() and the number of target comparisons:
Java
static public int binarySearch(int target, ArrayList integers,
int lower, int upper) {
static int recursions = 0; // Count recursive calls
static int comparisons = 0; // Count target comparisons
recursions++; // Increment recursion count
if (lower > upper) {
return -1; // Target not found
}
int mid = (lower + upper) / 2; // Calculate midpoint
comparisons++; // Count target comparison
if (target == integers.get(mid)) {
return mid; // Target found
} else if (target < integers.get(mid)) {
return binarySearch(target, integers, lower, mid - 1); // Search lower half
} else {
return binarySearch(target, integers, mid + 1, upper); // Search upper half
}
}
So, based on the above, in the main() method, one can be able to access the recursions as well as the comparisons variables like this:
Java
int index = binarySearch(target, integers, 0, integers.size() - 1);
System.out.printf("index: %d, recursions: %d, comparisons: %d\\",
index, recursions, comparisons);