Insertion Sort Example

by Donald White

JavaScript

const arr = [3, 8, 5, 4, 1, 9, -2];
const expected = [-3, 2, 3, 3, 4, 4, 5, 5, 6, 9, 56, 312];

const insertionSort = (arr, i = 0, n = arr.length - 1) => {
  const value = arr[i];
  let j = i;

  while (j > 0 && arr[j - 1] > value) {
    arr[j] = arr[j - 1];
    j--;
  }

  arr[j] = value;

  if (i + 1 <= n) {
    insertionSort(arr, i + 1, n);
  }
};


console.log('arr', arr);
console.log('insertionSort(arr)', insertionSort(arr));
console.log('arr', arr);

console.log(arr === expected ? 'pass' : 'fail');