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, stats) {
  const n = arr.length;
  let pass = 0;
  for (let gap = Math.floor(n / 2); gap > 0; gap = Math.floor(gap / 2)) {
    for (let i = gap; i < n; i++) {
      const temp = arr[i];
      let j = i;
      while (j >= gap) {
        compare(j - gap, i);
        if (arr[j - gap] <= temp) break;
        arr[j] = arr[j - gap];
        swap(j, j - gap);
        j -= gap;
      }
      arr[j] = temp;
      write(j, temp);
    }
    pass++;
    checkpoint(pass, Math.max(1, pass + 1));
  }
  for (let i = 0; i < n; i++) markSorted(i);
}