ProgrammingVery hardProduct company OA

What is printed?

What is printed?
int lb(const int *a, int n, int x) {
    int lo = 0, hi = n;
    while (lo < hi) {
        int mid = lo + (hi - lo) / 2;
        if (a[mid] < x) lo = mid + 1; else hi = mid;
    }
    return lo;
}
int main(void) {
    int a[] = {2, 4, 4, 4, 9, 9, 15};
    printf("%d %d %d %d", lb(a, 7, 4), lb(a, 7, 5), lb(a, 7, 16), lb(a + 2, 4, 9));
}
  1. A. 3 4 6 2
  2. B. 1 4 7 2
  3. C. 1 3 7 4
  4. D. 2 4 7 2

Correct answer: B. 1 4 7 2

With the half-open range [lo, hi) and 'hi = mid' on a[mid] ≥ x, the loop converges on the FIRST index whose element is ≥ x. For 4 that is index 1 (not the middle 4 that plain binary search would hit); for the absent 5 it is the insertion point 4; for 16 it is n = 7, one past the end – so a[lb] must not be read without a bounds check. a + 2 is the sub-array {4, 4, 9, 9}; the answer 2 is relative to that sub-array.

More C Programming questions

Exams that ask this topic