Data Structures & AlgorithmsModerateCognizant · Capgemini pattern

Binary search: how many iterations does this loop run to find x = 23?

Binary search: how many iterations does this loop run to find x = 23?
a = [2, 5, 8, 12, 16, 23, 38, 56, 72, 91]
lo, hi, it = 0, len(a) - 1, 0
while lo <= hi:
    it += 1
    mid = (lo + hi) // 2
    if a[mid] == 23: break
    if a[mid] < 23: lo = mid + 1
    else: hi = mid - 1
print(it, mid)
  1. A. 3 5
  2. B. 2 5
  3. C. 1 5
  4. D. 4 5

Correct answer: A. 3 5

First mid = 4 (16 < 23) → lo = 5; second mid = (5 + 9)//2 = 7 (56 > 23) → hi = 6; third mid = (5 + 6)//2 = 5 → found. 3 iterations, within the ⌊log₂ 10⌋ + 1 = 4 worst case. Linear search would need 6 comparisons.

More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions

Exams that ask this topic