ProgrammingHardAccenture · Cognizant
An array a = [1, 3, 5, 7, 9, 11, 13, 15] is searched with binary search for the target 15, and the procedure counts how many array elements are examined as mid values (one per loop iteration). What is printed?
An array a = [1, 3, 5, 7, 9, 11, 13, 15] is searched with binary search for the target 15, and the procedure counts how many array elements are examined as mid values (one per loop iteration). What is printed?
lo = 0; hi = n - 1; probes = 0
while lo <= hi
mid = (lo + hi) div 2; probes = probes + 1
if a[mid] == target then stop
if a[mid] < target then lo = mid + 1 else hi = mid - 1
end while
Print probes- A. 3
- B. 8
- C. 5
- D. 4
Correct answer: D. 4
The probes examine mid = 3 (7), mid = 5 (11), mid = 6 (13) and mid = 7 (15), so there are 4 probes. The lo < hi loop stops after 3 probes, the 1-based index of 15 is 8, and never checking for equality but adding one to the probe count gives 5.
Practise more Pseudocode and Code Tracing questionsPseudocode and Code Tracing: notes and key points
More Pseudocode and Code Tracing questions
- The procedure below converts the Roman numeral "MCMXCIV" to a number by reading left to right and subtracting a symbol's value when the…
- A recursive function is written as below. The procedure counts the calls made for input 7, including the first call. What is printed?…
- The procedure below uses exponentiation by squaring on the exponent 37. It counts one multiplication into result each time the current…
- Recursive merge sort splits an array of length n into halves of length n div 2 and n minus n div 2, and calls itself on each half unless…
- The loop below multiplies i by 3 each time while i is less than 1000, starting from i = 1, and counts the iterations. What is printed? i =…
- A nested loop counts the pairs (i, j) with 1 <= j <= i <= 6 that also satisfy i + j even. The procedure prints the count. What is printed?…