export const insertionSort = (arr = []) => {
  for (let i = 0; i < arr.length; i++) {
    let val = arr[i];
    let j = i - 1;
    while (j >= 0 && arr[j] > val) {
      arr[j + 1] = arr[j];
      j = j - 1;
    }
    arr[j + 1] = val;
  }
  return arr;
};
  1. Iterate from arr[1] to arr[N]
  2. Compare the current element (val) to its predecessor.
  3. If val is smaller than its predessor, compare it to the elements before. Move the greater elements one position up to make space for the swapped element.
Time Complexity: O(N2) as there are two nested Loops
Auxillary Space: O(1)

Try it out

Results:
Back to Learn