Insertion Sort

Algorithm (sentinel)

A[0] = -inf
for i = 2 to n do
	t = A[i]
	j = i-1
	while t < A[j] do
		A[j+1] = A[j]
		j = j-1
	A[j+1] = t

Comparisons

All comparisons occur in the while loop.

For the best case, the while loop never actually executes, requiring n1 comparisons.

For the worst case, the while loop executes until reaching the sentinel every time (reverse sorted).

The average case requires calculating the expected value. The outer summation with index i represents the for loop and the summation with index j calculates the expected value of comparisons for all possible elements A[i]. Since A[i] is equally likely to land anywhere in the subarray A[1i], take the expected value over all those possible positions.

Exchanges

For the purposes of this analysis we will also count the sentinel assignment.

For the best case, you only move to the temporary variable t and then move back to the array. This requires 2n1 exchanges.

For the worst case, you must move every sorted element. Instead of calculating a summation we can see there’s a relationship between comparisons in the worst case and moves. Inside the for loop we do one more move than comparison.

For the average case, we use apply the same relationship technique.

Algorithm (no sentinel)

for i = 2 to n do
	t = A[i]
	j = i-1
	while j > 0 and t < A[j] do
		A[j+1] = A[j]
		j = j-1
	A[j+1] = t

Comparisons

All comparisons occur in the while loop. We don’t count the boundary check as an extra comparison even if it would take time in real life.

For the best case, the while loop never actually executes, requiring n1 comparisons.

For the worst case, the while loop executes until reaching the edge of the array every time (reverse sorted).

The average case is equivalent to the non-sentinel version except we do no sentinel comparisons. Therefore, if we can calculate the average number of sentinel comparisons, we have our answer.

Therefore, the total comparisons is (n1)(n+4)4Hn+1.

Exchanges

This is not affected by the sentinel at all.