Skip to content

Insertion sort

ordering

Level 1 of 3

Also called Straight insertion.

fresh numbers

The test's questions that a run answers, asked again on new numbers whenever you like. The answer, its working and the reason for every other choice come from insertion sort's own run on the numbers shown.

choose one

question 1

Insertion sort works on 8, 3, 6, 1, 5. Its first slide places the 3. What is the row after its third slide?

83615
the answer, and why

the answer is A

Slide 1 gives 3, 8, 6, 1, 5. Slide 2 stops the 6 at the 3, giving 3, 6, 8, 1, 5. Slide 3 takes the 1 to the front, giving 1, 3, 6, 8, 5.

if you chose another

  • That is the row after slide 2.
  • That is the row sorted, after slide 4.
  • That stops the 1 at the 3, but the 3 is bigger too.

new numbers

question 2

How many comparisons does insertion sort make on 2, 5, 1, 4, 3, from start to finish?

25143
the answer, and why

the answer is A

The 5 makes 1. The 1 passes the 5 and the 2: 2, and reaching the front adds none. The 4 passes the 5 and stops at the 2: 2. The 3 passes the 5 and the 4 and stops at the 2: 3. So 1 + 2 + 2 + 3 = 8.

if you chose another

  • That counts the moves.
  • That is the most 5 numbers can cost, 1 + 2 + 3 + 4, on 5, 4, 3, 2, 1.
  • That is the fewest, one for each number placed, on 1, 2, 3, 4, 5.

new numbers

question 3

Each of these rows of 1 to 5 makes insertion sort move numbers exactly 4 times. On which does it make the most comparisons?

the answer, and why

the answer is C

Each number placed makes one comparison per move, plus one unless it reaches the front. All four rows make 4 moves, so the dearest has nothing reach the front. In 1, 3, 5, 4, 2 the 1 comes first and no slide reaches the front, so 4 moves plus 4 numbers placed, 4 + 4 = 8.

if you chose another

  • The 1 reaches the front, which saves a comparison, so this costs 7.
  • The 2 and the 1 reach the front, which saves two, so this costs 6.
  • The 1 reaches the front, which saves a comparison, so this costs 7.

new numbers