Question: Consider the following method, which implements a recursive binary search. /** Returns an index in arr where the value x appears if x appears *
Consider the following method, which implements a recursive binary search.
/** Returns an index in arr where the value x appears if x appears
* in arr between arr[left] and arr[right], inclusive;
* otherwise, returns -1.
* Precondition: arr is sorted in ascending order.
* left >= 0, right < arr.length, arr.length > 0
*/
public static int bSearch(int[] arr, int left, int right, int x)
{
if (right >= left)
{
int mid = (left + right) / 2;
if (arr[mid] == x)
{
return mid;
}
else if (arr[mid] > x)
{
return bSearch(arr, left, mid - 1, x);
}
else
{
return bSearch(arr, mid + 1, right, x);
}
}
return -1;
}
The following code segment appears in a method in the same class as bSearch.
int target = 10;
int[] arrWithDups = {2, 3, 7, 8, 10, 10, 10, 20};
int arrIndex = bSearch(arrWithDups, 0, arrWithDups.length - 1, target);
What is the value of arrIndex after the code segment has been executed?
-
A. 4
-
B. 5
-
C. 6
-
D. 7
-
E. 10
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
