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
  1. A. 3
  2. B. 8
  3. C. 5
  4. 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.

More Pseudocode and Code Tracing questions

Exams that ask this topic