Insertion Sort
Insertion Sort
Class: BS IT
The array is searched sequentially and unsorted items are moved and
inserted into the sorted sub-list (in the same array). This algorithm is not
suitable for large data sets as its average and worst case complexity are
of Ο(n2), where n is the number of items.
How Insertion Sort Works?
We take an unsorted array for our example.
14 33 27 10 35 19 42 44
14 33 27 10 35 19 42 44
It finds the both 14 and 33 are already in ascending order. For now, 14 is
in sorted sub-list.
14 33 27 10 35 19 42 44
Insertion sort moves ahead and compares 33 with 27.
14 33 27 10 35 19 42 44
14 33 27 10 35 19 42 44
It swaps 33 with 27. It also checks with the elements of sorted sub-list.
Here we see that the sorted sub-list has only one element 14 and 27 is
greater than 14. Hence, the sorted sub-list remains sorted after swapping.
14 27 33 10 35 19 42 44
By now we have 14 and 27 in the sorted sub-list. Next, it compares 33
with 10.
14 27 33 10 35 19 42 44
14 27 33 10 35 19 42 44
So we swap them.
14 27 10 33 35 19 42 44
However, swapping makes 27 and 10 unsorted.
14 27 10 33 35 19 42 44
14 10 27 33 35 19 42 44
14 10 27 33 35 19 42 44
We swap them again. By the end of the third iteration, we have a sorted
sub-list of 4 items.
10 14 27 33 35 19 42 44
This process goes on until all the unsorted values are covered in a sorted
sub-list. Now we shall see some programming aspects of insertion sort.
Algorithm
Now we have a bigger picture of how this sorting technique works, so we
can derive simple steps by which we can achieve insertion sort.