ProgrammingHardTCS NQT · Accenture pattern

What will be the output of the following pseudocode?

What will be the output of the following pseudocode?
Integer a[] = {1, 3, 5, 7, 9, 11, 13}
Integer lo = 0, hi = 6, t = 11, steps = 0, mid
while (lo <= hi)
    steps = steps + 1
    mid = (lo + hi) / 2
    if (a[mid] == t) break
    if (a[mid] < t) lo = mid + 1
    else hi = mid - 1
end while
Print mid, steps
  1. A. 5 3
  2. B. 4 2
  3. C. 5 2
  4. D. 6 2

Correct answer: C. 5 2

mid = 3 (7 < 11) → lo = 4; mid = (4 + 6)/2 = 5 → a[5] = 11 found. 2 iterations; a sorted array of 7 needs at most 3.

More Pseudocode and Code Tracing questions

Exams that ask this topic