Insertion Sort
for i = 2 to n
key = A[i]
j = i - 1
while j > 0 and A[j] > key
A[j + 1] = A[j]
j = j - 1
A[j + 1] = key- Sorting a deck of cards with hand.
Loop Invariant At the start of each iteration of the
forloop,the subarray
A[1:i - 1]consists of the elements originally inA[1:i - 1], but in sorted order.
- Best case: already sorted,
- Worst case: reversely sorted,
- Asymptotic proof
- Loops within loop,
- Assume the largest values occupy the first positions, each of them needs to be moved across positions in the middle, hence .