43B. The Cost of Insertion Sort


The cost of InsertCell

In the worst case, insertCell(C,L) needs to look at each member of list L once, and it takes a constant amount of time to look at one cell in L. Let's charge one unit of time to look at a cell in L, plus one unit of time to modify C. That gives n + 1 units of time, in the worst case, to do an insertion into a list of length n.


The cost of Insertion Sort

If list L has n members, then InsertionSort will do n calls to insertCell, one for each cell in L, since each cell needs to be inserted. If L is initially in reverse order, then each of those calls to insertCell will take its worst-case time.

The last cell in L will be inserted into an empty list, taking 1 unit of time according to our convention. The next-to-last cell in L will be inserted into a list of length 1, at a cost of 2 units. A little thought shows that the costs of the calls to insertCell, from the back of L to front of L, are: 1, 2, 3, 4, …, n, making the total cost of all of the calls to insertCell 1 + 2 + 3 + … + n.

Since 1 + 2 + 3 + … + n = n(n+1)/2, the time required to sort a linked list by Insertion Sort is Θ(n2).

That is quite slow. When n = 10,000, n2 is 100,000,000, or a hundred million.