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.
Watch an Insertion Sort
Sorting into ascending order (smallest to largest, or A to Z).
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
Compare & Shift
Is the highlighted item bigger than the one taken out? If so, shift it right. If not, insert the item here.
Insertion by Insertion
Type the list as it will be after the insertion, separated by commas.
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.
Run the Code
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.
Write & Mark
Complete the Explanation
Choose the right word for each gap.