Consider an Insertion Sort with a Sentinel on n values, where every value occurs exactly
twice in the input (so n must be even).
So the best case input for comparisons is when the elements are already sorted and the exact number of comparisons in the best case is n-1.
I believe the worst case input for comparisons is when the elements are reverse sorted. But what is the exact number of comparisons in this case? and why?
First, let’s walk through the best case. You have n elements. The first one you skip because there’s nothing before it to compare against, so there are only n-1 elements that might need to be moved. If an element does not need to be moved to the left, then we learn that after only one comparison. So if no elements need to be moved to the left (because the array is already sorted), then only 1 times n-1 comparisons are needed, hence n-1 total.
Now, if the array is reverse sorted, that means every element needs to be moved all the way to the left end of the array. We skip the 1st element as usual, so 0 comparisons there. The 2nd element moves 1 time after 1 comparison, the 3rd element moves 2 times after 2 comparisons, the 4th element moves 3 times after 3 comparisons…and so on. The nth element always requires n-1 comparisons to move all the way to the left. Thus the total number of comparisons for all n elements is 0+1+2+3+…+n-1, which summation formulas tell us is (n-1)((n-1)+1)/2 = (n-1)(n/2) comparisons, or alternatively O(n^2).
You are correct in believing that this scenario is a worst case for insertion sort. The algorithm’s outer loop can never have more than n iterations, and the ith inner loop can never have more than i iterations because we decrement j each time, so you end up with 0+1+2+3+…+n-1 as the maximum possible number of iterations of the inner loop for the whole algorithm (and the only comparison we care about is the one performed by an inner loop iteration). We could also try to sketch a proof that this is the only worst case scenario for insertion sort, but I’ll leave that as an exercise for now.