Block Sort

Stable in-place merge sort: recursively sorts the two halves, then merges them without an auxiliary array by rotating out-of-order runs into position (a block-rotation merge).

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

How it works

Stable in-place merge sort: recursively sorts the two halves, then merges them without an auxiliary array by rotating out-of-order runs into position (a block-rotation merge).

Implementation

function blockSort(arr) {
  const n = arr.length;
  const blockSize = Math.max(1, Math.floor(Math.sqrt(n)));
  // Sort each block with insertion sort
  for (let i = 0; i < n; i += blockSize) {
    const end = Math.min(i + blockSize, n);
    for (let j = i + 1; j < end; j++) {
      let key = arr[j], k = j - 1;
      while (k >= i && arr[k] > key) arr[k+1] = arr[k], k--;
      arr[k+1] = key;
    }
  }
  // Merge blocks in-place
  mergeBlocks(arr, blockSize);
}