External Merge Sort

Chunk-and-merge strategy modeling large-data sorting workflows beyond RAM.

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

How it works

Chunk-and-merge strategy modeling large-data sorting workflows beyond RAM.

Implementation

function externalMergeSort(arr, stats) {
  const n = arr.length;
  const chunkSize = Math.max(8, Math.floor(Math.sqrt(n || 1)));
  const chunks = [];
  for (let i = 0; i < n; i += chunkSize) {
    const chunk = arr.slice(i, Math.min(i + chunkSize, n));
    for (let p = 1; p < chunk.length; p++) {
      const key = chunk[p];
      let j = p - 1;
      while (j >= 0) {
        if (chunk[j] <= key) break;
        chunk[j + 1] = chunk[j];
        j--;
      }
      chunk[j + 1] = key;
    }
    chunks.push(chunk);
  }
  const ptr = new Array(chunks.length).fill(0);
  let out = 0;
  while (out < n) {
    let minChunk = -1;
    let minVal = 0;
    for (let c = 0; c < chunks.length; c++) {
      if (ptr[c] >= chunks[c].length) continue;
      const val = chunks[c][ptr[c]];
      if (minChunk === -1) {
        minChunk = c;
        minVal = val;
      } else {
        if (val < minVal) {
          minChunk = c;
          minVal = val;
        }
      }
    }
    arr[out] = minVal;
    ptr[minChunk]++;
    write(out, arr[out]);
    out++;
  }
}