You are on page 1of 5

INSERTION SORT

• Insertion sort keeps making the left side of the array


sorted until the whole array is sorted.
• It sorts the values seen far away and repeatedly inserts
unseen values in the array into the left sorted array.
• It is the simplest of all sorting algorithms.
• Although it has the same complexity as Bubble Sort, the
insertion sort is a little over twice as efficient as the
bubble sort.
• The disadvantage of Insertion Sort is that it is not
efficient to operate with a large list or input size.
• Real life example:
– An example of an insertion sort occurs in
everyday life while playing cards. To sort the
cards in your hand you extract a card, shift
the remaining cards, and then insert the
extracted card in the correct place. This
process is repeated until all the cards are in
the correct sequence.
Insertion sort for n=8 elements
Pass A[0] A[1] A[2] A[3] A[4] A[5] A[6] A[7] A[8]
K=1 - 77 33 44 11 88 22 66 55
K=2 - 77 33 44 11 88 22 66 55
K=3 - 33 77 44 11 88 22 66 55
K=4 - 33 44 77 11 88 22 66 55
K=5 - 11 33 44 77 88 22 66 55
K=6 - 11 33 44 77 88 22 66 55
K=7 - 11 22 33 44 77 88 66 55
K=8 - 11 22 33 44 66 77 88 55
Sorted - 11 22 33 44 55 66 77 88
Algorithm
INSERTION(A,N)
This algo sorts the array A with N elements

1. Set A[0]= -Infinite


2. Repeat Steps 3 to 5 for k= 2,3,…..N
3. Set TEMP:= A[K] and PTR := K-1
4. Repeat while TEMP < A[PTR]
(a)Set A[PTR+1] := A[PTR]
(b) Set PTR:= PTR -1
[End of loop]
5. Set A[PTR +1] := TEMP
[End of step 2 loop]
6. Return
Insertion Sort runtimes

• Best case: O(n). It occurs when the data is in


sorted order. After making one pass through
the data and making no insertions, insertion
sort exits.
• Average case: θ(n^2) since there is a wide
variation with the running time.
• Worst case: O(n^2) if the numbers were sorted
in reverse order.

You might also like