Question
Do a trace on the code below. In the method binarySearch below: variable key holds the value 27 , and variable a is a reference
Do a trace on the code below. In the method binarySearch below: variable key holds the value 27, and
variable a is a reference to an array with these values {12, 25, 36, 39, 43, 65, 78, 86, 99, 108, 121}.
public static int binarySearch(int[] list, int key) {
int lowIndex = 0;
int highIndex = list.length - 1;
while (highIndex >= lowIndex) {
int midIndex = (lowIndex + highIndex) / 2;
if (key < list[midIndex]){
highIndex = midIndex - 1;
}
else if (key > list[midIndex]){
lowIndex = midIndex + 1;
}
else if (key == list[midIndex]){
return midIndex;
}
} // end of while loop
return - 1;
} // end of binary search method
key | lowIndex | highIndex | midIndex | highIndex>=lowIndex | key==list[midIndex] | key |
27 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Given the key value and array content listed above, what is the return value of the binary search method? ___
Each row above correspond to one iteration of the while loop in the method above. You can add or remove rows according to the actual number of iterations. The search key value is set to 80.
How does the binary search work? (use simple words as if to explain to a non-technical person) __________________________________________________________________________________
__________________________________________________________________________________
__________________________________________________________________________________
__________________________________________________________________________________
__________________________________________________________________________________
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