For the following question, how will the array elements look after the second…

2024

For the following question, how will the array elements look after the second pass of Insertion Sort?

34, 8, 64, 51, 32, 21

  1. A.

    8, 21, 32, 34, 51, 64

  2. B.

    8, 32, 34, 51, 64, 21

  3. C.

    8, 34, 51, 64, 32, 21

  4. D.

    8, 34, 64, 51, 32, 21

Attempted by 16 students.

Show answer & explanation

Correct answer: D

Insertion sort builds the sorted portion of the array one element at a time. At the start of a pass, the first few elements already form a sorted prefix. The pass takes the next element -- the key -- and shifts every entry in that sorted prefix that is greater than the key one place to the right, then places the key into the gap left behind. If the key is already not smaller than the last element of the sorted prefix, no shifting happens at all -- the pass leaves the array unchanged.

  1. Start: 34, 8, 64, 51, 32, 21. The sorted prefix is just the first element, 34.

  2. Pass 1 (key = 8): compare 8 with 34, the only element of the sorted prefix. Since 34 is greater than 8, shift 34 one place to the right and place 8 at the front. The array becomes 8, 34, 64, 51, 32, 21.

  3. Pass 2 (key = 64): compare 64 with 34, the last element of the sorted prefix. Since 34 is not greater than 64, no shift is needed -- 64 stays exactly where it is. The array after the second pass remains 8, 34, 64, 51, 32, 21.

Continuing one more pass confirms the pattern: pass 3 takes key = 51, shifts 64 one place to the right, and gives 8, 34, 51, 64, 32, 21 -- a different array from the second-pass result, confirming that the second pass genuinely ends before 51 is touched.

Explore the full course: Coding For Placement

Loading lesson…