Watch insertion sort slide each value left into its place, like sorting cards in your hand. Worked example on 7 3 5 1 6, the code, and O(n) best to O(n²) worst.
About this algorithm
Insertion sort builds a sorted run on the left one value at a time, the way most people sort a hand of playing cards: it lifts the next value out, slides every bigger value in the sorted run one place to the right, and drops the lifted value into the gap. It takes O(n²) time on average and in the worst case, but on a list that is already nearly in order it does almost no work, down to O(n) when the list is already sorted.
Use insertion sort for small arrays, for data that arrives one item at a time and must stay sorted, and for lists that are already mostly in order: its running time depends on how many pairs are out of order, as well as on the length. That is why Timsort, the sort behind Python and Java's object sorting, uses insertion sort on short runs. It is stable and needs no extra memory. Selection sort makes fewer writes but always does the full n²/2 comparisons. Bubble sort does the same swaps as insertion sort with more comparisons. Once the list is large and scrambled, switch to merge sort, quick sort or heap sort.
A run of one value is already in order, so start with i = 1, the first value outside the run.
Copy the value at i into key. Its slot is now free to be overwritten.
Set j = i - 1. While j is at least 0 and the value at j is bigger than key, copy the value at j one slot right and move j one slot left. Stop at the first value that is not bigger, or when j runs off the front.
Write key into slot j + 1. The run from 0 to i is sorted again. Move i one place right until it passes the end.
This page opens on 40 random bars, so type 7,3,5,1,6 into the Custom box to follow along. Key 3: 7 is bigger and slides right, and 3 drops into index 0, giving 3 7 5 1 6. Key 5: 7 slides right, 3 is smaller, so 5 lands at index 1: 3 5 7 1 6. Key 1: 7, 5 and 3 each slide right and 1 runs to the front: 1 3 5 7 6. Key 6: only 7 slides, and 6 lands at index 3: 1 3 5 6 7. That is 6 shifts, and the input had exactly 6 pairs out of order (7 before 3, 5, 1 and 6, then 3 before 1 and 5 before 1). Each shift fixes one such pair, which is why a nearly sorted list finishes so fast.
A common first version swaps the key backwards one neighbour at a time. That works, but each swap writes two slots. Holding the key aside and shifting writes each moved value once, then writes the key once at the end.
Time: each key does one comparison plus one shift for every bigger value before it, so a sorted list costs n - 1 comparisons and a reversed one about n²/2 shifts. Space: it works in place and only holds the key and two indices.