ProgrammingVery hardCompetitive coding (CP)

What is printed for the sorted array below?

What is printed for the sorted array below?
#include <stdio.h>
int main(void) {
    int a[] = {1, 3, 3, 3, 5, 8};
    int n = 6, lo = 0, hi = n;
    while (lo < hi) {
        int m = lo + (hi - lo) / 2;
        if (a[m] < 3) lo = m + 1; else hi = m;
    }
    int lb = lo;
    lo = 0; hi = n;
    while (lo < hi) {
        int m = lo + (hi - lo) / 2;
        if (a[m] <= 3) lo = m + 1; else hi = m;
    }
    printf("%d %d", lb, lo);
}
  1. A. 1 3
  2. B. 1 4
  3. C. 0 4
  4. D. 1 5

Correct answer: B. 1 4

The first search finds the lower bound of 3, which is index 1. The second finds the first index whose value is greater than 3, which is index 4.

More C Programming questions

Exams that ask this topic