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

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!