Pairwise Sorting Network

Ian Parberry's pairwise sorting network (1992): a data-oblivious network with the same number of comparators and depth as Batcher's odd-even mergesort, but a distinct structure. Compare-exchanges that fall outside the array are pruned, so the fixed schedule sorts any length in place with no extra memory.

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

How it works

Ian Parberry's pairwise sorting network (1992): a data-oblivious network with the same number of comparators and depth as Batcher's odd-even mergesort, but a distinct structure. Compare-exchanges that fall outside the array are pruned, so the fixed schedule sorts any length in place with no extra memory.

Implementation

function pairwiseNetworkSort(arr, stats) {
  const n = arr.length;
  if (n < 2) {
    if (n === 1) markSorted(0);
    return;
  }
  let k = 1;
  while (k < n) k <<= 1;
  function compareExchange(i, j) {
    compare(i, j);
    if (arr[i] > arr[j]) {
      swap(i, j);
      const t = arr[i];
      arr[i] = arr[j];
      arr[j] = t;
    }
  }
  for (let p = k >> 1; p >= 1; p >>= 1) {
    for (let a = 0; a < n; a += p * 2) {
      for (let b = 0; b < p; b++) {
        const j = a + b + p;
        if (j < n) compareExchange(a + b, j);
      }
    }
    for (let q = k >> 1; q >= p * 2; q >>= 1) {
      for (let c = 0; c < n; c += p * 2) {
        for (let d = 0; d < p; d++) {
          const j = c + d + q;
          if (j < n) compareExchange(c + d + p, j);
        }
      }
    }
    checkpoint(k - p, k);
  }
  for (let i = 0; i < n; i++) markSorted(i);
}