ProgrammingVery hardCompetitive coding (CP)
What is printed?
What is printed?
#include <stdio.h>
int bs(const int *a, int lo, int hi, int k) {
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[] = {1, 3, 5, 7, 9, 11};
printf("%d %d", bs(a, 0, 5, 9), bs(a, 0, 5, 4));
}- A. 4 -1
- B. 3 -1
- C. 5 -1
- D. 4 0
Correct answer: A. 4 -1
9 sits at index 4, and the value 4 is absent, so the search returns -1 once lo exceeds hi. The recursive halving visits only log n positions.
More C Programming questions
- What is printed? c #include <stdio.h> int main(void) { int a[] = {5, 9, 12, 7}; int p[5] = {0}; for (int i = 0; i < 4; i++) p[i + 1] =…
- What is printed? c #include <stdio.h> int add(int a, int b) { return a + b; } int sub(int a, int b) { return a - b; } int mul(int a, int…
- What is printed? c #include <stdio.h> int main(void) { signed char c = -1; unsigned char d = c; printf("%d %d", c == d, (int)d); }
- What is printed? c #include <stdio.h> int main(void) { int h = -17; unsigned idx = (unsigned)h % 16u; printf("%u", idx); }
- What is printed? c #include <stdio.h> #include <stdlib.h> #include <string.h> struct Person { char name[4]; int age; }; int cmp(const void…
- What is printed? c #include <stdio.h> int main(void) { int a[] = {3, 1, 2, 5, 4}, c = 0; for (int i = 0; i < 5; i++) for (int j = i + 1; j…