ProgrammingVery hardCompetitive coding (CP)

How many comparisons does bsearch-style binary search make to find the key 6 in the sorted array 0 to 9? Compute with the program.

How many comparisons does bsearch-style binary search make to find the key 6 in the sorted array 0 to 9? Compute with the program.
#include <stdio.h>
int main(void) {
    int a[10], lo = 0, hi = 9, k = 6, probes = 0;
    for (int i = 0; i < 10; i++) a[i] = i;
    while (lo <= hi) {
        int m = (lo + hi) / 2;
        probes++;
        if (a[m] == k) break;
        if (a[m] < k) lo = m + 1;
        else hi = m - 1;
    }
    printf("%d", probes);
}
  1. A. 3
  2. B. 2
  3. C. 5
  4. D. 4

Correct answer: D. 4

The probes examine indices 4, 7, 5 and then 6, so the key is found on the fourth probe.

More C Programming questions

Exams that ask this topic