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;
  if (n < 2) return;
  const block = Math.max(2, Math.floor(Math.sqrt(n)));
  for (let lo = 0; lo < n; lo += block) {
    const hi = Math.min(lo + block, n);
    for (let i = lo + 1; i < hi; i++) {
      const key = arr[i];
      let j = i - 1;
      while (j >= lo && arr[j] > key) {
        arr[j + 1] = arr[j];
        j--;
      }
      arr[j + 1] = key;
    }
  }
  const temp = new Array(n).fill(0);
  for (let width = block; width < n; width *= 2) {
    for (let lo = 0; lo < n; lo += 2 * width) {
      const mid = Math.min(lo + width, n);
      const hi = Math.min(lo + 2 * width, n);
      if (mid >= hi) continue;
      let i = lo;
      let j = mid;
      let k = lo;
      while (i < mid && j < hi) {
        if (arr[i] <= arr[j]) {
          temp[k] = arr[i];
          i++;
        } else {
          temp[k] = arr[j];
          j++;
        }
        k++;
      }
      while (i < mid) {
        temp[k] = arr[i];
        i++;
        k++;
      }
      while (j < hi) {
        temp[k] = arr[j];
        j++;
        k++;
      }
      for (let p = lo; p < hi; p++) {
        arr[p] = temp[p];
      }
    }
  }
}