ProgrammingHardCapgemini · Infosys pattern

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 arr[6] = {5, 2, 9, 1, 5, 6}
for (each i from 1 to length(arr) - 1)
    Integer key = arr[i]
    Integer j = i - 1
    while (j >= 0 and arr[j] > key)
        arr[j + 1] = arr[j]
        j = j - 1
    end while
    arr[j + 1] = key
end for
Print arr
  1. A. [1, 2, 5, 5, 6, 9]
  2. B. [5, 2, 9, 1, 5, 6]
  3. C. [1, 2, 5, 6, 5, 9]
  4. D. [9, 6, 5, 5, 2, 1]

Correct answer: A. [1, 2, 5, 5, 6, 9]

This is insertion sort: each key is shifted left past larger elements until it finds its correct spot. Applying it to {5,2,9,1,5,6} fully sorts the array into [1, 2, 5, 5, 6, 9].

More Pseudocode and Code Tracing questions

Exams that ask this topic