cachaito
2/14/2020 - 9:36 PM

Insertion sorting algorithm

function insertionSort(array) {
  for(let i = 1; i < array.length; i++) {
    let temp = array[i];
    let j = i - 1;

    while(array[j] > temp) {
      array[j+1] = array[j];
      j--;
    }

    j++;

    array[j] = temp;
  }

  return array;
}

var sorted = insertionSort([23000, 444, 1, 999, 0]);
console.log(sorted); // [0, 1, 444, 999, 23000]