Insertion Sort
Insertion Sort
Insertion Sort
Insertion Sort
What is Insertion Sort?
An element that is to be 'inserted' into this sorted
sub-list must first locates its proper location and
then be inserted there. As a result, the term
"insertion sort" was formed.
now i = 2, element = 3
compare element with its left side values and swap them
6 > 3 --> true --> swap --> 5 3 6 1 8 7 2 4
5 > 3 --> true --> swap --> 3 5 6 1 8 7 2 4
now i = 3, element = 1
compare element(1) with its left side values and sort them.
6 > 1 --> true --> swap --> 3 5 1 6 8 7 2 4
5 > 1 --> true --> swap --> 3 1 5 6 8 7 2 4
3 > 1 --> true --> swap --> 1 3 5 6 8 7 2 4
now i = 4, element = 8
compare element (8) with its left side values and sort them. 6 > 8 --> false
--> no swap. that means all left side values are already sorted.
now i = 5, element = 7
compare element (7) with its left side values and sort them.
8 > 7 --> true --> swap --> 1 3 5 6 7 8 2 4
6 > 7 --> false --> no swap. All left side values are already sorted.
now i = 6, element 2
compare element (2) with its left side values and sort them.
8 > 2 --> true --> swap --> 1 3 5 6 7 2 8 4
7 > 2 --> true --> swap --> 1 3 5 6 2 7 8 4
6 > 2 --> true --> swap --> 1 3 5 2 6 7 8 4
5 > 2 --> true --> swap --> 1 3 2 5 6 7 8 4
3 > 2 --> true --> swap --> 1 2 3 5 6 7 8 4
1 > 2 --> false --> no swap. that means all left side values are
already sorted.
now i = 7, element 4
compare key(4) with its left side values and sort them.
8 > 4 --> true --> swap --> 1 2 3 5 6 7 4 8
7 > 4 --> true --> swap --> 1 2 3 5 6 4 7 8
6 > 4 --> true --> swap --> 1 2 3 5 4 6 7 8
5 > 4 --> true --> swap --> 1 2 3 4 5 6 7 8
3 > 4 --> false --> no swap. that means all left side values
are already sorted.
Reached end of array and stops processing.