ProgrammingVery hardCompetitive coding (CP)
How many iterations does this binary search make to find 13 in the sorted array 0 to 15? Compute with the program.
How many iterations does this binary search make to find 13 in the sorted array 0 to 15? Compute with the program.
#include <stdio.h>
int probes(const int *a, int n, int k) {
int lo = 0, hi = n - 1, p = 0;
while (lo <= hi) {
int m = lo + (hi - lo) / 2;
p++;
if (a[m] == k) return p;
if (a[m] < k) lo = m + 1;
else hi = m - 1;
}
return p;
}
int main(void) {
int a[16];
for (int i = 0; i < 16; i++) a[i] = i;
printf("%d", probes(a, 16, 13));
}- A. 4
- B. 2
- C. 3
- D. 5
Correct answer: C. 3
The probes examine index 7, then 11, then 13, so the value 13 is found on the third comparison. Counting the array size's halving steps gives 4.
More C Programming questions
- n <= 10^5 values, each up to 10^9, must be summed. Which declaration is correct for the total?
- To test whether n = 10^12 is prime by trial division up to sqrt(n), which loop is correct?
- A middle index of a range [lo, hi] is needed for hi near INTMAX. Which expression is safe?
- A scanf loop reads integers until the end of input. Which loop is correct when the input may end with a non-numeric token?
- A character loop reads bytes with char c = getchar() and tests while (c != EOF). Why can this loop be wrong?
- To count occurrences of values up to 10^6 in O(n), which code is correct and fast enough?