Steps:
- pick up the next item in the list
- look at all the previous elements in the list, and move it to the appropriate position
- repeat until we've done all the items
e.g. for
[12, 6, 21, 5, 9]
- we start with
12
. There are no previous elements, so we move onto the next item. - We look at
6
. Comparing it to the only previous element6
we can see that we want to move it before12
, so our list should look like[6, 12, 21, 5, 9]
. - We look at
21
, and compare it to the previous elements. First we compare21
and12
– clearly21
is greater than12
(and we know that the previous elements must all be sorted, so we can stop there). - We look at
5
.5
is smaller than21
, so we compare it to the previous element.5
is also smaller than12
so we turn to look at6
.5
is less than6
. Therefore our list is now[5, 6, 12, 21, 9]
- We now look at
9
.9
is less than21
, so we look at12
.9
is less than12
, so we look at6
.9
is greater than6
, so we insert9
after6
. Our list is now[5, 6, 9, 12, 21]
The final list is therefore [5, 6, 9, 12, 21]
.