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));
}
  1. A. 4
  2. B. 2
  3. C. 3
  4. 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

Exams that ask this topic