How insertion sort works
The array is split into a sorted prefix and an unsorted rest. For each index i, the value arr[i] is saved as key. A second index j walks left through the prefix, shifting every value larger than key one place to the right, and key is written into the gap that opens up.
The example sorts [8, 3, 5, 1, 9, 2]. Watch the 1: it has to travel past every value before it, which is exactly the work a reverse-sorted input would force on every element.
What to watch for when it runs
- The sorted prefix grows by one cell on each pass of the outer loop.
- Shifts are writes, not swaps — values copy one place right, and key is written only once, at the end.
- The execution count on the while line shows how far each key had to travel.
Time and space complexity
- Time
- O(n²) worst case, O(n) when already sorted
- Space
- O(1)
Each element moves once for every larger value before it, so the running time is O(n + inversions) — which is why it is the sort of choice for small or nearly-sorted inputs.