ProgrammingVery hardCompetitive coding (CP)

What is printed?

What is printed?
#include <stdio.h>
int calls = 0;
int bs(int *a, int lo, int hi, int k) {
    calls++;
    if (lo > hi) return -1;
    int m = lo + (hi - lo) / 2;
    if (a[m] == k) return m;
    return a[m] < k ? bs(a, m + 1, hi, k) : bs(a, lo, m - 1, k);
}
int main(void) {
    int a[16];
    for (int i = 0; i < 16; i++) a[i] = i;
    printf("%d %d", bs(a, 0, 15, 16), calls);
}
  1. A. -1 6
  2. B. -1 5
  3. C. -1 7
  4. D. 16 6

Correct answer: A. -1 6

Key 16 is absent, so the search returns -1 after the recursion reaches an empty range. The six calls cover the intervals [0,15], [8,15], [12,15], [14,15], [15,15] and [16,15].

More C Programming questions

Exams that ask this topic