OCR J277 · 2.1.3 Searching and Sorting Algorithms

Insertion Sort

Mr Brown

What Is an Insertion Sort?

An insertion sort puts a list in order by taking each item in turn and inserting it into the correct place among the items before it, which are already sorted. Larger items are shifted one place to the right to make a gap. Each insertion adds one more item, so the sorted part grows from the left.

Interactive Demo

Watch an Insertion Sort

Sorting into ascending order (smallest to largest, or A to Z).

Item being insertedBeing comparedJust shiftedSorted part
Insertion 0
Comparisons 0
Shifts 0

The steps

  • Treat the first item as the sorted part (a list of one item is already in order)
  • Take the next item in the list, leaving a gap
  • Compare it with the items in the sorted part, working from right to left
  • Shift each item that is bigger one place to the right
  • When you reach an item that is not bigger (or the start of the list), put the item into the gap — that is one insertion
  • Repeat until every item has been inserted — the list is sorted

Pre-requisites

  • The data must be in a list (an array) whose items can be compared and put in order — numbers, or text in alphabetical order
  • The list does not need to be sorted already

Try It

Interactive Practice

Compare & Shift

Is the highlighted item bigger than the one taken out? If so, shift it right. If not, insert the item here.

Insertion 1
Right first time 0 / 0
Interactive Practice

Insertion by Insertion

Type the list as it will be after the insertion, separated by commas.

Insertions right 0 / 0

The Algorithm

In the exam, an insertion sort may be shown as code or in OCR Exam Reference Language. You don't need to remember it, but you must recognise it and explain what each part does. Click a line to see what it does, or step through it.

Interactive Demo

Run the Code

i
j
temp
insertion
list

How to spot an insertion sort

  • An outer loop that starts at index 1 and takes each item in turn (temp = list[i])
  • An inner while loop that works backwards through the items to the left (j goes down)
  • Items shifted right (list[j + 1] = list[j]), then temp placed in the gap

Sample Questions

Write your answer, then reveal the mark scheme and tick each point you included.

Interactive Practice

Write & Mark

Interactive Practice

Complete the Explanation

Choose the right word for each gap.

Insertion Sort Challenges

Complete

0

Points

0
Challenge

Loading challenge…