Data Structures & AlgorithmsHardTCS Digital · Infosys pattern

Insertion sort (shift larger elements right; one key comparison per inner-loop test) sorts [2, 4, 1, 3, 5] into ascending order. How many key comparisons does it make in total?

  1. A. 4
  2. B. 5
  3. C. 6
  4. D. 10

Correct answer: C. 6

i=1: 4 vs 2 (1). i=2: 1 vs 4, 1 vs 2, then j reaches −1 with no further comparison (2). i=3: 3 vs 4, 3 vs 2 stop (2). i=4: 5 vs 4 stop (1). Total 6. The number of SHIFTS (inversions) is 3; '10' is the worst case n(n−1)/2.

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

Exams that ask this topic