Professional Documents
Culture Documents
Algorithm
WEEK 5
Real life scenario
Insertion sort
Insertion sort is a simple sorting algorithm that builds the final sorted array
one item at a time by comparisons.
It is much less efficient on large lists than more advanced algorithms such as
quicksort, heapsort, or merge sort.
Why is it called insertion sort?
An element which is to be inserted in this sorted sub-list, has to find its
appropriate place and then it has to be inserted there. Hence the name,
insertion sort.
The array is searched sequentially and unsorted items are moved and inserted
into the sorted sub-list (in the same array).
Algorithm
Insertion Algorithms: Steps on how it works:
If it is the first element, it is already sorted.
Pick the next element.
Compare with all the elements in sorted sub-list.
Shift all the elements in sorted sub-list that is greater than the value to be
sorted.
Insert the value.
Repeat until list is sorted
Complexity
Worst complexity: n^2
Average complexity: n^2
Best complexity: n
Space complexity: 1
Method: Insertion
Stable: Yes
Class: Comparison sort
Example
Insertion sort is a simple sorting algorithm that works similar to the way
you sort playing cards in your hands.
The array is virtually split into a sorted and an unsorted part.
Values from the unsorted part are picked and placed at the correct position
in the sorted part.
Now sort the following according to
Selection sort:
19 34 11 1 49 21 41
Now sort the following according to
Selection sort:
83 91 4 52 95 71 36
Now sort the following according to
Selection sort:
54 49 37 4 85 24 18