Two simple way to insertion sort

Two simple way to insertion sort in JavaScript

function InsertionSort(arr) {
  const len = arr.length;

  for (let i = 1; i < len; i++) {
    let current = arr[i];
    let x = i - 1;

    while (x >= 0 && arr[x] > current) {
      arr[x + 1] = arr[x];
      x--;
    }
    arr[x + 1] = current;

  }
  return arr;
}

const InsertionSortNew = arr => {
  arr.forEach( (item , i ) => {    
    let x;
    for (x = i - 1; x >= 0 && arr[x] > item; x--) {
      arr[x + 1] = arr[x];
    };
    arr[x + 1] = item;
  });
  return arr;
}

const unsortedArray = [44, 3, 34, 1, 96, 8, 20, 4];
console.log("Unsorted array", unsortedArray);

const sortedArray = InsertionSort(unsortedArray);
console.log("Insertion Sort 1: ", "Sorted array", sortedArray);

const sortedArrayNew = InsertionSortNew(unsortedArray);
console.log("Insertion Sort 2: ", "Sorted array", sortedArrayNew);
(Visited 2 times, 1 visits today)

Leave a comment

Your email address will not be published. Required fields are marked *