Data Structures & AlgorithmsHardCognizant · Capgemini pattern

while (lo <= hi) binary search runs on a sorted array of 31 elements for a key LARGER than every element. How many times does the loop body run?

  1. A. 31
  2. B. 5
  3. C. 6
  4. D. 4

Correct answer: B. 5

The range shrinks 31 → 15 → 7 → 3 → 1 → 0, one iteration per halving while the range is non-empty: 5 iterations (log₂ 32 = 5). 4 forgets the last one-element check; 6 counts the failing loop test as an iteration.

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

Exams that ask this topic