Insertion sort an array - Node.js Algorithm

Node.js examples for Algorithm:Sort

Description

Insertion sort an array

Demo Code


function insertionSort(arr) {
  var temp, j;/*  w ww. j  a va2s  . c o  m*/
  for (var i = 1, len = arr.length; i < len; i++) {
    temp = arr[i];
    j = i - 1;
    while (j >= 0 && arr[j] > temp) {
      arr[j + 1] = arr[j];
      j--;
    }
    arr[j + 1] = temp;
  }
  return arr;
}

Related Tutorials