🎙 Free live masterclass · Sun, 29 Nov, 7:00 pm IST · Java Full Stack roadmap Register free →
Skills101
← Quiz: Sorting Basics: all 13 questions

Quiz: Sorting Basics · Question 9 of 13

What does this print? (code)

What does this print?

a = [4, 3, 2, 1]
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, 4] 3
  2. B.[1, 2, 3, 4] 4
  3. C.[1, 2, 3, 4] 6
  4. D.[4, 3, 2, 1] 0
Answer & explanation

Correct answer: [1, 2, 3, 4] 6

A reverse-sorted array is insertion sort's worst case: every pair is out of order, so it needs 4 × 3 / 2 = 6 shifts.

Can you get the rest right without peeking?

Take the timed Quiz: Sorting Basics quiz free. Pass it to earn XP and count towards your certificate.

Start the quiz →