ProgrammingHardTCS NQT · Accenture pattern

What will be the output of the following pseudocode (moving all zeros to the end while preserving the relative order of non-zero elements, in place)? (Arrays are indexed from 0.)

What will be the output of the following pseudocode (moving all zeros to the end while preserving the relative order of non-zero elements, in place)? (Arrays are indexed from 0.)
Integer arr[5] = {0, 1, 0, 3, 12}
Integer write = 0
for (each read from 0 to 4)
    if (arr[read] != 0)
        swap(arr[write], arr[read])
        write = write + 1
    end if
end for
Print arr
  1. A. [1, 3, 12, 0, 0]
  2. B. [0, 0, 1, 3, 12]
  3. C. [1, 0, 3, 0, 12]
  4. D. [0, 1, 3, 12, 0]

Correct answer: A. [1, 3, 12, 0, 0]

Every non-zero element is swapped forward into the 'write' position in order encountered (1, 3, 12), pushing the zeros naturally to the back: [1, 3, 12, 0, 0].

More Pseudocode and Code Tracing questions

Exams that ask this topic