ProgrammingHardAccenture · Cognizant

Binary search for the value 13 in the sorted array [1, 3, 5, 7, 9, 11, 13, 15, 17, 19] uses lo = 0, hi = n - 1 and mid = (lo + hi) div 2. Each loop iteration is one probe (one mid examined). How many probes are made before the value is found?

Binary search for the value 13 in the sorted array [1, 3, 5, 7, 9, 11, 13, 15, 17, 19] uses lo = 0, hi = n - 1 and mid = (lo + hi) div 2. Each loop iteration is one probe (one mid examined). How many probes are made before the value is found?
lo = 0; hi = n - 1; probes = 0
while lo <= hi
    mid = (lo + hi) div 2; probes = probes + 1
    if a[mid] == 13 then stop
    else if a[mid] < 13 then lo = mid + 1 else hi = mid - 1
end while
Print probes
  1. A. 4
  2. B. 7
  3. C. 3
  4. D. 5

Correct answer: A. 4

The probes examine mid = 4 (9), mid = 7 (15), mid = 5 (11), and mid = 6 (13), which is 4 probes. Counting the 1-based position gives 7, stopping one probe early gives 3, and adding one to the final count gives 5.

More Pseudocode and Code Tracing questions

Exams that ask this topic