GATE Computer ScienceVery hardGATE CS (PYQ pattern)

Insertion sort on [7, 3, 9, 1, 8, 2, 6, 5, 4] scans left-to-right from position j = i − 1, comparing a[j] with the key until a[j] ≤ key or j falls below 0 (each such test is one comparison). How many key comparisons are made in total?

  1. A. 27
  2. B. 21
  3. C. 29
  4. D. 25

Correct answer: A. 27

Shifts equal the number of inversions, 21. Each of the 8 insertions also makes one terminating comparison (a[j] ≤ key), except when the scan runs off the left end, which happens when the key is a new minimum (keys 3 and 1): 21 + 8 − 2 = 27. Counting only inversions (21) forgets the terminating comparisons.

More Algorithms questions

Exams that ask this topic