ProgrammingVery hardProduct company OA · code-tracing level

What will be the output of the following pseudocode? (Arrays are indexed from 0; / is integer division.)

What will be the output of the following pseudocode? (Arrays are indexed from 0; / is integer division.)
Integer a[7] = {1, 3, 5, 5, 5, 7, 9}, x = 5
Integer lo = 0, hi = 7, mid, steps = 0
while (lo < hi)
    mid = (lo + hi) / 2
    steps = steps + 1
    if (a[mid] < x)
        lo = mid + 1
    else
        hi = mid
    end if
end while
Print lo, steps
  1. A. 2 3
  2. B. 3 3
  3. C. 2 2
  4. D. 4 3

Correct answer: A. 2 3

This is a lower-bound search: it finds the first index whose value is ≥ x. Trace: (0, 7) → mid 3, a[3] = 5 ≥ 5, hi = 3; (0, 3) → mid 1, a[1] = 3 < 5, lo = 2; (2, 3) → mid 2, a[2] = 5, hi = 2. lo = hi = 2 after 3 steps. '3 3' assumes the search stops at the first 5 it meets (index 3), as an ordinary binary search would.

More Pseudocode and Code Tracing questions

Exams that ask this topic