ProgrammingHardTCS NQT · Infosys · Capgemini pattern

What will be the output of the following pseudocode? (All variables are integers, so / is integer division. Array is sorted and indexed from 0.)

What will be the output of the following pseudocode? (All variables are integers, so / is integer division. Array is sorted and indexed from 0.)
Integer arr[37] = {2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58, 60, 62, 64, 66, 68, 70, 72, 74}
Integer lo = 0, hi = 36, steps = 0, target = 12
while (lo <= hi)
    steps = steps + 1
    Integer mid = (lo + hi) / 2
    if (arr[mid] == target)
        Print steps
        break
    else if (arr[mid] < target)
        lo = mid + 1
    else
        hi = mid - 1
    end if
end while
  1. A. 6
  2. B. 4
  3. C. 3
  4. D. 5

Correct answer: B. 4

Binary search on 37 elements halves the range each step. Tracing mid = (lo+hi)/2 at each step until arr[mid] == 12 (at index 5) takes exactly 4 step(s) for this particular target position — not simply ceil(log2(37)) = 6, which is only the worst case.

More Pseudocode and Code Tracing questions

Exams that ask this topic