Given an array of integers nums, sort the array in ascending order using the Insertion Sort algorithm — build up a sorted prefix one element at a time by inserting each new element into its correct position among the already-sorted elements to its left.
nums = [8,4,3,7,6][3,4,6,7,8]Invariant: before processing index i, nums[0..i-1] is always sorted. We pull nums[i] out as key, then repeatedly shift the sorted prefix's elements one step right wherever they exceed key, opening a gap that walks left. As soon as we hit an element ≤ key (or run off the front), the gap is key's correct resting spot — dropping it in there keeps nums[0..i] sorted, extending the invariant by one. On already-sorted input, the inner loop never shifts, giving the O(n) best case.
It is O(n²) in the worst case. But on nearly sorted data it is very fast, which is why libraries use it for small parts.
Keep the left part of the array sorted. Take the next value as the key. Shift every bigger value in the sorted part one step to the right. Drop the key into the gap that opens up. Repeat until the whole array is the sorted part.
Shift bigger values right, then drop the key into the gap. Insertion sort shines on small or nearly sorted inputs.
Run the animation above on your own input, or watch the 1:36 video explanation of Insertion Sort with a dry run and Java code.