ProgrammingHardTCS NQT · Accenture

Insertion sort on the array [5, 2, 4, 6, 1, 3] shifts an element one place right each time it moves past a larger element. The procedure below counts those shifts. What is printed?

Insertion sort on the array [5, 2, 4, 6, 1, 3] shifts an element one place right each time it moves past a larger element. The procedure below counts those shifts. What is printed?
shifts = 0
for i = 1 to n - 1
    key = a[i]; j = i - 1
    while j >= 0 and a[j] > key
        a[j+1] = a[j]; j = j - 1; shifts = shifts + 1
    end while
    a[j+1] = key
end for
Print shifts
  1. A. 5
  2. B. 10
  3. C. 9
  4. D. 15

Correct answer: C. 9

Each shift removes one inversion, and this array has 9 inversions, so 9 shifts happen. Counting the outer passes gives 5, counting comparisons (including each failed test) gives 10, and adding n to the total gives 15.

More Pseudocode and Code Tracing questions

Exams that ask this topic