Insertion sort works the way most people sort a hand of playing cards: pick up the next card and slide it left into its place among the cards already sorted. It is simple, it is fast on small or nearly sorted data, and it never reorders equal values.
The array is split into two parts by a boundary that moves from left to right:
Each pass does the same three things:
arr[i], into a variable called key. Its slot is now free.After n − 1 passes every value has been inserted, so the whole array is sorted.
Sorting {12, 11, 13, 5, 6}. Blue cells are the sorted part; the yellow cell is the key being inserted in that pass.
The array in main() changes to match what you sort.
Best case: already sorted. Each key is compared once with its left neighbor, which is not bigger, so nothing moves. That is n − 1 comparisons and no shifts: O(n).
Worst case: reversed. Each key is smaller than everything in the sorted part, so it travels all the way to the front. Pass i makes i comparisons and i shifts, for a total of
1 + 2 + … + (n − 1) = n(n − 1) / 2
which is O(n²). Random data needs about half that: still O(n²).
Insertion sort is adaptive: the closer the data is to sorted, the less work it does. A nearly sorted array costs barely more than n comparisons. It sorts in place with O(1) extra memory (just key, i and j).
5: one per key, each against its left neighbor. No values move. Compare that with selection sort, which always makes 15.
The sorted part starts as just arr[0]. A single value is already sorted, so the first value to insert is arr[1].
A value is shifted only when it is strictly bigger than the key (arr[j] > key). An equal value stays put, so the key stops just to its right, and equal values never jump over each other. Changing > to >= would break this.
The first shift writes arr[i - 1] into arr[i], overwriting the value we are inserting. Saving it in key first keeps it safe.