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));
}- A. 3 4 6 2
- B. 1 4 7 2
- C. 1 3 7 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
- What is printed? c int a = 7, b = 2; double x = a / b; double y = (double)a / b; double z = (double)(a / b); int w = (int)(-3.7) +…
- What is printed? c enum { RED = 2, GREEN, BLUE = GREEN + 4, N }; int a[] = { [RED] = 5, [BLUE] = 1, 9, [GREEN] = 6, 4 }; printf("%zu %d %d…
- Assume 8-bit char, 16-bit unsigned short and 32-bit int. What is printed? c int big = 300; unsigned char uc = big; unsigned short us = -1…
- What is printed? c int slot(int i) { static int box[3]; return &box[i % 3]; } int main(void) { slot(0) = 5; slot(4) = 7; int p = slot(3)…
- What is printed? c #define A 1 #define B #if defined(B) && A + C #define X 10 #else #define X 20 #endif #undef A #ifdef A #define Y 1…
- An array of int that may contain any values from INTMIN to INTMAX is sorted with qsort. With int x = (const int )a, y = (const int )b…