Shell sort an array - Node.js Algorithm

Node.js examples for Algorithm:Sort

Description

Shell sort an array

Demo Code

function shellSort(arr) {
  var len = arr.length;
  var h = 1;// w  w  w  .  j  a v a2s.c  om

  // set h based on 3x+1 sequence
  while (h < len / 3) h = 3 * h + 1; // 1, 4, 13, 40, 121...

  while (h >= 1) {
    for (var i = h; i < len; i++) {
      for (var j = i; j >= h; j -= h) {
        if (arr[j] < arr[j - h]) swap(arr, j, j - h);
      }
    }
    h = Math.floor(h / 3);
  }
  return arr;
}

Related Tutorials