ProgrammingHardCompetitive coding (CP)

In the sorted array {1, 3, 4, 4, 7}, what index is printed by this lower-bound search for key 4?

In the sorted array {1, 3, 4, 4, 7}, what index is printed by this lower-bound search for key 4?
#include <stdio.h>
int main(void) {
    int a[] = {1, 3, 4, 4, 7}, lo = 0, hi = 5, k = 4;
    while (lo < hi) {
        int m = lo + (hi - lo) / 2;
        if (a[m] < k) lo = m + 1;
        else hi = m;
    }
    printf("%d", lo);
}
  1. A. 3
  2. B. 2
  3. C. 1
  4. D. 4

Correct answer: B. 2

The lower bound is the first index whose value is at least 4, which is index 2. The search only moves lo past values strictly less than 4.

More C Programming questions

Exams that ask this topic