ProgrammingHardAmazon OA · Goldman Sachs OA

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

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

Correct answer: A. 3 12 3

This binary search climbs towards a peak. mid = 2: 8 < 12, lo = 3; mid = 4: 4 > 2, hi = 4; mid = 3: 12 > 4, hi = 3. Stops after 3 steps at index 3: 3 12 3.

More Pseudocode and Code Tracing questions

Exams that ask this topic