Insertion Sort
Insertion Sort
STRUCTURES
MAHESH GOYANI
MAHATMA GANDHI INSTITUE OF TECHNICAL EDUCATION & RESEARCH CENTER
[email protected]
In plain English: for each element starting with the second, “pull”
the element, then look at all earlier elements and shift larger ones
to the right, then insert the element
In pseudo code:
for each element from second to last
save the element
for each earlier element that is larger
shift it right
insert current element
4 512
4 512
4512
4 512
4512
34512
4 512
4512
34512
4 512 34 52
4512
34512
4 512 34 52
4512 3 452
34512
4 512 34 52
4512 3 452
34512 3452
4 512 34 52
4512 3 452
34512 3452
13452
(C) GOYANI MAHESH 13
45312 34512 13452
4 512 34 52
4512 3 452
34512 3452
13452
(C) GOYANI MAHESH 14
45312 34512 13452
4 512 34 52 134 5
4512 3 452
34512 3452
13452
(C) GOYANI MAHESH 15
45312 34512 13452
4 512 34 52 134 5
4512 3 452 13 45
34512 3452
13452
(C) GOYANI MAHESH 16
45312 34512 13452
4 512 34 52 134 5
4512 3 452 13 45
13452
(C) GOYANI MAHESH 17
45312 34512 13452
4 512 34 52 134 5
4512 3 452 13 45
13452 12345
(C) GOYANI MAHESH 18
SIMMULATION
5 2 4 6 1 3
2 5 44 6 1 3
2 4 5 6 1 3
2 4 5 6 1 3
1 2 4 5 6 3
1 2 3 4 5 6
Done!
sorted
Analysis of the code shows that the outer loop executes n-1 times;
for the first iteration of the outer loop, the inner loop executes
1 time
for the second iteration of the outer loop, the inner loop
executes, in the worst case, 2 times
etc
for the last iteration of the outer loop, the inner loop executes ,
in the worst case, n-1 time
thus the execution time is 1 + 2 + 3 + … + (n-2) + (n-1)
the sum of this series is (n2 - n) / 2
insertion sort is O(n2 )