I had a question on a test – I got it wrong, but I don’t know why?
Question: An array of integers is to be sorted from biggest to smallest using an insertion sort. Assume the array originally contains the following elements:
5 9 17 12 2 14
What will it look like after the third pass through the for loop?
17 9 5 12 2 14
17 12 9 5 2 14 – Correct answer
17 12 9 5 14 2
17 14 12 9 5 2
9 5 17 12 2 14
In an insertion sort, I thought the source array is untouched; I felt, at the third pass, the destination array would be incomplete.
How did the test arrive at this answer?
Basically, after
npasses of insertion sort, the firstn+1elements are sorted in the correct order and the rest are untouched. As you can see in the alternatives, the correct answer is the only one that fulfills that. Every step is only inserting relative to the already sorted numbers, so each step one extra number is correctly sorted.Step 0 (Original,
5assumed sorted)Step 1, takes the 9 and puts it in the correct place before 5 (result,
9 5sorted)Step 2, takes the 17 and puts it in the correct place before 9 (result
17 9 5sorted)Step 3, takes the 12 and puts it in the correct place after 17 and before 9 (result
17 12 9 5sorted)