Tournament Sort

Builds a winner tree (a tournament bracket): adjacent players compete in rounds and the smaller value advances. The champion is output, its leaf is retired, and only the single path from that leaf back to the root is replayed in O(log n) before the next champion emerges.

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

How it works

Builds a winner tree (a tournament bracket): adjacent players compete in rounds and the smaller value advances. The champion is output, its leaf is retired, and only the single path from that leaf back to the root is replayed in O(log n) before the next champion emerges.

Implementation

function tournamentSort(arr, stats) {
  const n = arr.length;
  if (n < 2) {
    if (n === 1) markSorted(0);
    return;
  }
  let size = 1;
  while (size < n) size <<= 1;
  const values = new Array(size);
  for (let i = 0; i < n; i++) values[i] = arr[i];
  for (let i = n; i < size; i++) values[i] = Infinity;
  const tree = new Array(2 * size).fill(-1);
  for (let i = 0; i < size; i++) tree[size + i] = i;
  for (let node = size - 1; node >= 1; node--) {
    const left = tree[2 * node];
    const right = tree[2 * node + 1];
    tree[node] = values[left] <= values[right] ? left : right;
  }
  for (let out = 0; out < n; out++) {
    const winner = tree[1];
    const championValue = values[winner];
    arr[out] = championValue;
    write(out, championValue);
    markSorted(out);
    values[winner] = Infinity;
    let node = size + winner >> 1;
    while (node >= 1) {
      const left = tree[2 * node];
      const right = tree[2 * node + 1];
      tree[node] = values[left] <= values[right] ? left : right;
      node >>= 1;
    }
    checkpoint(out + 1, n);
  }
}