ProgrammingHardGoldman Sachs OA · TCS Digital

What will be the output of the following pseudocode?

What will be the output of the following pseudocode?
Integer a[6] = {5, 2, 4, 6, 1, 3}, shifts = 0, key, j
for (each i from 1 to 5)
    key = a[i]
    j = i - 1
    while (j >= 0 AND a[j] > key)
        a[j + 1] = a[j]
        shifts = shifts + 1
        j = j - 1
    end while
    a[j + 1] = key
end for
Print shifts
  1. A. 5
  2. B. 9
  3. C. 15
  4. D. 8

Correct answer: B. 9

Each shift in insertion sort removes exactly one inversion, so shifts = number of inversions of {5, 2, 4, 6, 1, 3} = 4 + 1 + 2 + 2 + 0 = 9.

More Pseudocode and Code Tracing questions

Exams that ask this topic