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);
}- A. 3
- B. 2
- C. 1
- 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
- How many of these statements are true for unsigned x = 5? Print the count from this program. c #include <stdio.h> int main(void) {…
- What is printed? c #include <stdio.h> int main(void) { int a[] = {5, 6, 7}, p = a + 1; printf("%d", p[-1] + p + p[1]); }
- How many tilings does a 2 by 5 board have with 2 by 1 dominoes? Compute with this recursive program. c #include <stdio.h> int f(int n) {…
- What is printed? c #include <stdio.h> #include <stdlib.h> int v[] = {30, 10, 20}; int cmp(const void a, const void b) { int i = (const int…
- What is printed? c #include <stdio.h> #include <stdlib.h> int cmp(const void a, const void b) { unsigned x = (const unsigned )a, y =…
- How many numbers from 1 to 100 have bit 3 set (value 8)? Compute with this program. c #include <stdio.h> int main(void) { int c = 0; for…