ProgrammingVery hardCompetitive coding (CP)
How many comparisons does bsearch-style binary search make to find the key 6 in the sorted array 0 to 9? Compute with the program.
How many comparisons does bsearch-style binary search make to find the key 6 in the sorted array 0 to 9? Compute with the program.
#include <stdio.h>
int main(void) {
int a[10], lo = 0, hi = 9, k = 6, probes = 0;
for (int i = 0; i < 10; i++) a[i] = i;
while (lo <= hi) {
int m = (lo + hi) / 2;
probes++;
if (a[m] == k) break;
if (a[m] < k) lo = m + 1;
else hi = m - 1;
}
printf("%d", probes);
}- A. 3
- B. 2
- C. 5
- D. 4
Correct answer: D. 4
The probes examine indices 4, 7, 5 and then 6, so the key is found on the fourth probe.
More C Programming questions
- What is printed? c #include <stdio.h> int main(void) { int s = 0; for (unsigned i = 0; i < 8; i++) s += (i ^ (i >> 1)) & 1u; printf("%d"…
- What is printed? Assume int is 32 bits. c #include <stdio.h> int main(void) { int a = -3; unsigned b = 2; printf("%u", a b); }
- What is printed? c #include <stdio.h> int main(void) { unsigned a = 7; printf("%u", a / 2 2); }
- What is printed? c #include <stdio.h> int f(int n) { static int memo[10]; if (n < 2) return n; if (memo[n]) return memo[n]; return memo[n]…
- What is printed? c #include <stdio.h> int main(void) { printf("%c", 'a' + ('z' - 'a') / 2); }
- How many trailing one bits does 0x1F3 have? Compute with this program. c #include <stdio.h> int main(void) { unsigned x = 0x1F3; int c =…