try to identify how many iterations to find number 19 in the sequence of 1 2 3 5
ID: 3594760 • Letter: T
Question
try to identify how many iterations to find number 19 in the sequence of
1 2 3 5 6 7 8 10 12 13 15 16 18 19 20 22
// Returns the index of an occurrence of target in a,
// or a negative number if the target is not found.
// Precondition: elements of a are in sorted order
public static int binarySearch(int[] a, int target) {
int min = 0;
int max = a.length - 1;
while (min <= max) {
int mid = (min + max) / 2;
if (a[mid] < target) {
min = mid + 1;
} else if (a[mid] > target) {
max = mid - 1;
} else {
return mid; // target found
}
}
return -(min + 1); // target not found
}
Explanation / Answer
It will take three iteratins to find the element 19.
In the first iteration it will compare with a[7]
In the second iteration it will compare with a[11]
In the third iteration it will compare with a[13] and the target matches and the function returns
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.