Data Structures & AlgorithmsModerateTCS NQT · sorting

Problem: How many swaps does insertion sort perform on [3, 2, 1]? Count the shifts in the code.

Problem: How many swaps does insertion sort perform on [3, 2, 1]? Count the shifts in the code.
a = [3, 2, 1]
swaps = 0
for i in range(1, len(a)):
    j = i
    while j > 0 and a[j - 1] > a[j]:
        a[j - 1], a[j] = a[j], a[j - 1]
        swaps += 1
        j -= 1
print(swaps)
What is printed?
  1. A. 3
  2. B. 2
  3. C. 1
  4. D. 6

Correct answer: A. 3

Insertion sort performs one swap per inversion, and [3,2,1] has 3 inversions.

More Coding Interview Problems questions

Exams that ask this topic