ProgrammingHardAmazon OA · Infosys SP

What will be the output of the following pseudocode?

What will be the output of the following pseudocode?
Integer a[6] = {1, 2, 3, 4, 5, 6}
Integer i = 0, j = 5
while (i < j)
    if (a[i] mod 2 == 0)
        i = i + 1
    else if (a[j] mod 2 == 1)
        j = j - 1
    else
        swap(a[i], a[j])
        i = i + 1
        j = j - 1
    end if
end while
Print a[0], a[1], a[2], a[3], a[4], a[5]
  1. A. 2 4 6 1 3 5
  2. B. 6 4 2 3 5 1
  3. C. 2 4 6 5 3 1
  4. D. 6 2 4 3 5 1

Correct answer: D. 6 2 4 3 5 1

The two-pointer partition moves even numbers to the front by swapping, without keeping order. 1 ↔ 6, then 3 ↔ 4 (2 is already even): {6, 2, 4, 3, 5, 1}. The stable answer 2 4 6 1 3 5 would need a different method.

More Pseudocode and Code Tracing questions

Exams that ask this topic