Lecture 1 - An Introduction
In the first iteration of the loop we need to check if the first element of the list is sorted. This is trivially true.
On the jth loop, the first j+1 elements of the list are sorted.
It is easy to see that the newly considered element is placed in the position of the smallest element that is greater than the new element.
It is easy to see that the key is placed in the position of the smallest element amongst the j - 1 first elements that is greater than the key.
It is also easy to see that all elements greater than the key have their index increased by one, so the key is correctly sorted with respect to its larger elements.
The new element is correctly sorted with respect to its smaller elements as it replaced a larger element and the original j - 1 elements were correctly sorted at the beginning of the loop.
Now we only need to check the original j -1 elements are correctly sorted. Pick an arbitrary element which was not the key.
Assume the index of the element was increased during the loop. This means it was greater than the key.
Since the index of any element can be increased by at most one, this means the element is still sorted with respect to its smaller elements.
Likewise, if the index of the element was increased, so was the index of its greater elements. So, the chosen element is still correctly sorted with respect to its larger elements.
Thus we conclude that any element that had its index increased is still sorted correctly.
If an element did not have its index increased, then neither did its smaller elements, so the element is still sorted with respect to its smaller elements.
Since the index of an existing element cannot be decreased, the element must still be sorted with respect to its greater elements.
Thus any element whose index did not change is still correctly sorted.
Since we have covered all cases the step case is now complete!
We have shown by induction that at the end of every loop j , the first j elements of the list are sorted.
Since the loop runs for n steps, where n is the length of the list, we conclude that the list must be fully sorted once it terminates!
Hence insertion sort solves the sorting problem!