Question: Given the following Java function, answer the following questions. public static int binarySearch ( int [ ] array, int searchKey ) { int lowerBound =

Given the following Java function, answer the following questions.
public static int binarySearch(int[] array, int searchKey){
int lowerBound =0, upperBound = array.length -1;
while (true){
int middle =(lowerBound + upperBound)/2;
if (array[middle]== searchKey)
return middle;
else if (searchKey > array[middle])
lowerBound = middle +1;
else
upperBound = middle -1;
}
}
1) Suppose we are calling the above function below, write down the values of lowerBound and
upperBound during each while loop. At last, describe the returned result.
int[] array ={1,3,5,8,10,11};
System.out.println(binarySearch(array,7));
2) Suppose the parameter array contains random elements in increasing order and array does not
contain searchKey, we call the above method. After a certain amount of time, both lowerBound
and upperBound will point to the same index, suppose its value is x. We have two scenarios here:
array[x]> searchKey and array[x]< searchKey. Find out the values of lowerBound
and upperBound during the next three loops for each scenario.

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 Programming Questions!