Data Structures & AlgorithmsModerateTCS NQT · Accenture

Problem: Binary search for the value 77 in the sorted list 1, 2, ..., 100 uses the midpoint mid = (lo + hi) // 2 and the inclusive range [lo, hi] starting from [0, 99]. How many comparisons (midpoints examined) are needed?

  1. A. 5
  2. B. 7
  3. C. 6
  4. D. 77

Correct answer: B. 7

Midpoints 49, 74, 87, 80, 77, 75, 76 (indices) are examined, finding value 77 at index 76 on the seventh. Searching for index 77 gives 5, not counting the final hit gives 6, and a linear scan needs 77.

More Coding Interview Problems questions

Exams that ask this topic