Data Structures & AlgorithmsModerateTCS NQT · Infosys pattern

Insertion sort counts element shifts. What is printed?

Insertion sort counts element shifts. What is printed?
a = [3, 7, 1, 5, 2]
shifts = 0
for i in range(1, len(a)):
    key, j = a[i], i - 1
    while j >= 0 and a[j] > key:
        a[j + 1] = a[j]; j -= 1; shifts += 1
    a[j + 1] = key
print(a, shifts)
  1. A. [1, 2, 3, 5, 7] 5
  2. B. [1, 2, 3, 5, 7] 6
  3. C. [1, 2, 3, 5, 7] 7
  4. D. [1, 2, 3, 5, 7] 4

Correct answer: B. [1, 2, 3, 5, 7] 6

The number of shifts equals the number of inversions: (3,1), (3,2), (7,1), (7,5), (7,2), (5,2) = 6. On sorted input insertion sort makes 0 shifts (O(n)); on reversed input n(n−1)/2.

More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions

Exams that ask this topic