Tutorial 6
📥
Insertion Sort
9618 A-Level
i
It may be useful to search (CTRL + F) for "insertion sort" questions in the (combined) past papers
If you find any bugs/edge cases in this code, please contact me
1
Insertion Sort
For IGCSE/O-Level/AS, you should be familiar with bubble sort along with its two optimisations
Both sorting algorithms have a time complexity of O(n2) - e.g. in the worst case, if we have an array of 10 elements, we might have to do approximately 100 comparisons, if we have 1 million elements, we might have to do 1 trillion comparisons etc
There are more efficient sorting algorithms available (good video comparing their performance), however these are either too difficult/time-consuming to code for an A-Level exam and/or require significant additional memory - bubble sort and insertion sort are both "in place" sorting algorithms, meaning they don't require additional data structures/copies of the data to function
Let's see how insertion sort works:
- Start at n + 1 (e.g. the 2nd element on the first loop) and copy it to a temporary variable
- If the previous value (n) is greater than the temp variable, then shift it one position right in the array
- Continue shifting elements right until you find an element smaller than the temp variable
- "Drop" the temp variable at this index location
- Increment from n and repeat from step 1 - do this for all remaining indexes of n
This .gif from Wikipedia shows the algorithm visually:

More detailed comments can be seen in the code
Extension details/answers will be added: compare with bubble sort - try with completely random arrays, nearly sorted, completely unsorted (e.g. reverse order) - which algorithm generally performs less comparisons?