Best, Worst, and Average Cases
The best case input is an array that is already sorted. In this case insertion sort has a linear running time (i.e., Θ(n)). During each iteration, the first remaining element of the input is only compared with the right-most element of the sorted subsection of the array.
The simplest worst case input is an array sorted in reverse order. The set of all worst case inputs consists of all arrays where each element is the smallest or second-smallest of the elements before it. In these cases every iteration of the inner loop will scan and shift the entire sorted subsection of the array before inserting the next element. This gives insertion sort a quadratic running time (i.e., O(n2)).
The average case is also quadratic, which makes insertion sort impractical for sorting large arrays. However, insertion sort is one of the fastest algorithms for sorting very small arrays, even faster than quicksort; indeed, good quicksort implementations use insertion sort for arrays smaller than a certain threshold, also when arising as subproblems; the exact threshold must be determined experimentally and depends on the machine, but is commonly around ten.
Example: The following table shows the steps for sorting the sequence {3, 7, 4, 9, 5, 2, 6, 1}. In each step, the item under consideration is underlined. The item that was moved (or left in place because it was biggest yet considered) in the previous step is shown in bold.
3 7 4 9 5 2 6 1
3 7 4 9 5 2 6 1
3 7 4 9 5 2 6 1
3 4 7 9 5 2 6 1
3 4 7 9 5 2 6 1
3 4 5 7 9 2 6 1
2 3 4 5 7 9 6 1
2 3 4 5 6 7 9 1
1 2 3 4 5 6 7 9
Read more about this topic: Insertion Sort
Famous quotes containing the words average and/or cases:
“The average educated man in America has about as much knowledge of what a political idea is as he has of the principles of counterpoint. Each is a thing used in politics or music which those fellows who practise politics or music manipulate somehow. Show him one and he will deny that it is politics at all. It must be corrupt or he will not recognize it. He has only seen dried figs. He has only thought dried thoughts. A live thought or a real idea is against the rules of his mind.”
—John Jay Chapman (18621933)
“Only by being guilty of Folly does mortal man in many cases arrive at the perception of Sense. A thought which should forever free us from hasty imprecations upon our ever-recurring intervals of Folly; since though Folly be our teacher, Sense is the lesson she teaches; since, if Folly wholly depart from us, Further Sense will be her companion in the flight, and we will be left standing midway in wisdom.”
—Herman Melville (18191891)