Data Structures & AlgorithmsHardGATE CS

Insertion sort (stable, scanning leftwards while a[j] > key) sorts [6, 3, 9, 3, 1, 8, 2, 7, 5, 4]. Counting every evaluation of the comparison a[j] > key, how many comparisons are made in total?

  1. A. 28
  2. B. 31
  3. C. 34
  4. D. 24

Correct answer: B. 31

Each element makes (number of larger elements to its left) + 1 comparisons unless it reaches the front, giving 31 in total; the number of inversions alone is 24.

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

Exams that ask this topic