Sqrt Sort

Hybrid stable approach using square-root-sized buffers and blockwise merging.

Best O(n) Avg O(n log n) Worst O(n log n) Space O(√n) Stable Yes In-place No Comparison-based

How it works

Hybrid stable approach using square-root-sized buffers and blockwise merging.

Implementation

function sqrtSort(arr, stats) {
  const n = arr.length;
  const block = Math.max(2, Math.floor(Math.sqrt(n || 1)));
  function insertion(lo, hi) {
    for (let i = lo + 1; i <= hi; i++) {
      const key = arr[i];
      let j = i - 1;
      while (j >= lo) {
        compare(j, i);
        if (arr[j] <= key) break;
        arr[j + 1] = arr[j];
        write(j + 1, arr[j + 1]);
        j--;
      }
      arr[j + 1] = key;
      write(j + 1, key);
    }
  }
  const temp = new Array(n);
  function merge(lo, mid, hi) {
    let i = lo;
    let j = mid + 1;
    let k = lo;
    while (i <= mid && j <= hi) {
      compare(i, j);
      temp[k++] = arr[i] <= arr[j] ? arr[i++] : arr[j++];
    }
    while (i <= mid) temp[k++] = arr[i++];
    while (j <= hi) temp[k++] = arr[j++];
    for (let p = lo; p <= hi; p++) {
      arr[p] = temp[p];
      write(p, arr[p]);
    }
  }
  for (let i = 0; i < n; i += block) insertion(i, Math.min(i + block - 1, n - 1));
  for (let width = block; width < n; width <<= 1) {
    for (let i = 0; i < n; i += width << 1) {
      const lo = i;
      const mid = Math.min(i + width - 1, n - 1);
      const hi = Math.min(i + (width << 1) - 1, n - 1);
      if (mid < hi) merge(lo, mid, hi);
    }
  }
}