Skip to content

JavaScript Shell Sort Algorithm

Ramesh Fadatare edited this page Jul 11, 2019 · 1 revision
function shellSort(array, compareFn = defaultCompare) {
  let increment = array.length / 2;
  while (increment > 0) {
    for (let i = increment; i < array.length; i++) {
      let j = i;
      const temp = array[i];
      while (j >= increment && compareFn(array[j - increment], temp) === Compare.BIGGER_THAN) {
        array[j] = array[j - increment];
        j -= increment;
      }
      array[j] = temp;
    }
    if (increment === 2) {
      increment = 1;
    } else {
      increment = Math.floor((increment * 5) / 11);
    }
  }
  return array;
}

const Compare = {
  LESS_THAN: -1,
  BIGGER_THAN: 1,
  EQUALS: 0
};

function defaultCompare(a, b) {
  if (a === b) {
    return Compare.EQUALS;
  }
  return a < b ? Compare.LESS_THAN : Compare.BIGGER_THAN;
}

let array = [2,1,5,4,3,8,7,6];
array = shellSort(array);
console.log(array);

Output:

[1, 2, 3, 4, 5, 6, 7, 8]
Clone this wiki locally