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.