Answers for "how to do an insertion sort in javascript"

1

javascript insertion sort

const insertionSort = array => {
  const arr = Array.from(array); // avoid side effects
  for (let i = 1; i < arr.length; i++) {
    for (let j = i; j > 0 && arr[j] < arr[j - 1]; j--) {
      [arr[j], arr[j - 1]] = [arr[j - 1], arr[j]];
    }
  }
  return arr;
};

console.log(insertionSort([4, 9, 2, 1, 5]));
Posted by: Guest on March-29-2021

Code answers related to "how to do an insertion sort in javascript"

Code answers related to "Javascript"

Browse Popular Code Answers by Language