Show that insertion sort has worst case performance O(N2)
Insertion sort has worst case performance as O(N2) when input array is already sorted but in non-ascending order.
For example consider the array below.
N N-1 N-2 ............. 6 5 4 3 2 1
1st Element N will not be compared with anyone => 0 Comparisons.
2nd Element N-1 will be compared to N. N-1 and N will be swapped => 1 comparison
N-1 N N-2 ............. 6 5 4 3 2 1
3rd Element N-2 will be compared to N. N-2 and N will be swapped then N-2 will be compared with N-1. N-1 and N-2 will be swapped. => 2 comparisons
N-2 N-1 N ............. 6 5 4 3 2 1
Similarly
(N-1)th element 2 will be compared to N, N-1, N-2, ... 3 => N-2 Comparisons
Nth element 1 will be compared to N, N-1, N-2, ... 2 => N-1 Comparisons
1 2 3 4 5 6 ........... N-2 N-1 N
So, total number of comparisons
Get Answers For Free
Most questions answered within 1 hours.