ProgrammingHardTCS NQT · Infosys · Capgemini

What will be the output of the following pseudocode? (Division is integer division; arrays are 0-indexed.)

What will be the output of the following pseudocode? (Division is integer division; arrays are 0-indexed.)
Integer a[9] = {2, 3, 3, 3, 5, 8, 8, 13, 21}
Integer lo = 0, hi = 9, steps = 0
While lo < hi
    Integer mid = (lo + hi) / 2
    If a[mid] < 8 Then
        lo = mid + 1
    Else
        hi = mid
    End If
    steps = steps + 1
End While
Print lo, steps
  1. A. 6 3
  2. B. 7 3
  3. C. 5 4
  4. D. 5 3

Correct answer: C. 5 4

This is a lower-bound search: it finds the first index whose value is at least 8, which is index 5 (the first 8). The interval shrinks 9 -> 4 -> 2 -> 1 -> 0, and the loop ends after the number of steps shown; using <= instead of < would return index 7.

More Pseudocode and Code Tracing questions

Exams that ask this topic