Shell Sort

Generalizes insertion sort to allow exchanges of elements far apart. Uses a decreasing sequence of gap values.

Best O(n log n) Avg O(n^(4/3)) Worst O(n^(3/2)) Space O(1) Stable No In-place Yes Comparison-based

How it works

Generalizes insertion sort to allow exchanges of elements far apart. Uses a decreasing sequence of gap values.

Implementation

function shellSort(arr) {
  for (let gap = Math.floor(arr.length/2); gap > 0;
       gap = Math.floor(gap/2)) {
    for (let i = gap; i < arr.length; i++) {
      let temp = arr[i], j = i;
      while (j >= gap && arr[j - gap] > temp) {
        arr[j] = arr[j - gap];
        j -= gap;
      }
      arr[j] = temp;
    }
  }
}