3-Way Quicksort

Quicksort partitioning into less/equal/greater regions, especially strong on duplicate-heavy input.

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

How it works

Quicksort partitioning into less/equal/greater regions, especially strong on duplicate-heavy input.

Implementation

function quick3WaySort(arr, stats) {
  const n = arr.length;
  function sort(lo, hi) {
    if (lo >= hi) return;
    const pivot = arr[lo];
    let lt = lo;
    let i = lo + 1;
    let gt = hi;
    while (i <= gt) {
      compare(i, lo);
      if (arr[i] < pivot) {
        if (i !== lt) {
          swap(i, lt);
          const t = arr[i];
          arr[i] = arr[lt];
          arr[lt] = t;
        }
        i++;
        lt++;
      } else if (arr[i] > pivot) {
        swap(i, gt);
        const t = arr[i];
        arr[i] = arr[gt];
        arr[gt] = t;
        gt--;
      } else {
        i++;
      }
    }
    sort(lo, lt - 1);
    sort(gt + 1, hi);
  }
  sort(0, n - 1);
}