Strand Sort

Pulls sorted "strands" from the input and merges them into the output list. Very efficient for partially sorted data.

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

How it works

Pulls sorted "strands" from the input and merges them into the output list. Very efficient for partially sorted data.

Implementation

function strandSort(arr, stats) {
  const n = arr.length;
  if (n <= 1) return;
  let input = arr.slice();
  let output = [];
  function mergeArrays(a, b) {
    const result = [];
    let i = 0, j = 0;
    while (i < a.length && j < b.length) {
      if (a[i] <= b[j]) result.push(a[i++]); else result.push(b[j++]);
    }
    while (i < a.length) {
      result.push(a[i++]);
    }
    while (j < b.length) {
      result.push(b[j++]);
    }
    return result;
  }
  let pass = 0;
  while (input.length > 0) {
    const strand = [input[0]];
    const remaining = [];
    for (let i = 1; i < input.length; i++) {
      if (input[i] >= strand[strand.length - 1]) {
        strand.push(input[i]);
      } else {
        remaining.push(input[i]);
      }
    }
    input = remaining;
    output = mergeArrays(output, strand);
    pass++;
    for (let i = 0; i < output.length; i++) {
      arr[i] = output[i];
      write(i, output[i]);
    }
    checkpoint(pass, pass + input.length);
  }
  for (let i = 0; i < n; i++) markSorted(i);
}