ProgrammingVery hardAmazon OA · Goldman Sachs OA

What will be the output of the following pseudocode? (Arrays are indexed from 0)

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

Correct answer: C. 2 4

This is the Dutch-national-flag partition. It ends with all 0's in a[0..lo − 1] and all 2's in a[hi + 1..7]. There are two 0's and three 2's, so lo = 2 and hi = 7 − 3 = 4.

More Pseudocode and Code Tracing questions

Exams that ask this topic