Data Structures & AlgorithmsModerate

Insertion sort (ascending) is run on 6 3 8 1 5. Each time the inner loop compares the key with an element to its left, that is one comparison. How many comparisons are made in total?

  1. A. 6
  2. B. 4
  3. C. 8
  4. D. 14

Correct answer: C. 8

Insertions: 3 (1 comparison), 8 (1), 1 (3, reaching the front), 5 (3: past 8 and 6, stopping at 3): total 8. The 6 shifts (inversions) undercount because each early stop also costs a comparison; 4 is the best case n − 1, and 14 adds shifts and comparisons.

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

Exams that ask this topic