Question
Consider the following method, which implements a recursive binary search. /** Returns an index in nums where target appears if target * appears in nums
Consider the following method, which implements a recursive binary search.
/** Returns an index in nums where target appears if target
* appears in nums between nums[lo] and nums[hi], inclusive;
* otherwise, returns -1.
* Precondition: nums is sorted in ascending order.
* lo >= 0, hi < nums.length, nums.length > 0
*/
public static int bSearch(int[] nums, int lo, int hi, int target)
{
if (hi >= lo)
{
int mid = (lo + hi) / 2;
if (nums[mid] == target)
{
return mid;
}
if (nums[mid] > target)
{
return bSearch(nums, lo, mid - 1, target);
}
else
{
return bSearch(nums, mid + 1, hi, target);
}
}
return -1;
}
The following code segment appears in a method in the same class as bSearch.
int target = 3;
int[] nums = {2, 4, 6, 8, 10, 12, 14, 16, 18, 20};
int targetIndex = bSearch(nums, 0, nums.length - 1, target);
How many times will bSearch be called as a result of executing the code segment above?
A. 1
B. 2
C. 3
D. 4
E. 5
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started