To determine the average efficiency of insertion sort consider the number
of times that the inner loop iterates. As with other loops featuring
nested loops, the number of iterations follows a familiar pattern:
1 + 2 + ... + (n - 2) + (n - 1) = n(n - 1) = O(n2). Conceptually, the above
pattern is caused by the sorted sublist that is built throughout the
insertion sort algorithm. It takes one iteration to build a sorted
sublist of length 1, 2 iterations to build a sorted sublist of length two
and finally n-1 iterations to build the final list. To determine whether
there are any best or worst cases for the sort, we can examine the algorithm
to find data sets that would behave differently from the average case with
random data. Because the average case identified above locally sorts each
sublist there is no arrangement of the aggregate data set that is
significantly worse for insertion sort. The nature of the
sorting algorithm
does however lend itself to perform more efficiently on certain data. In
the case where the data is already sorted, insertion sort won't have to do
any shifting because the local sublist will already be sorted. That is,
the first element will already be sorted, the first two will already be
sorted, the first three, and so on. In this case, insertion sort will
iterate once through the list, and, finding no elements out of order, will
not shift any of the data around. The best case for insertion sort is on
a sorted list where it runs is
O(n).