Stable Quicksort

Quicksort that preserves the order of equal elements by partitioning each range into less / equal / greater buffers and writing them straight back, so every level visibly regroups the bars in place. The equal block lands in its final position immediately.

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

How it works

Quicksort that preserves the order of equal elements by partitioning each range into less / equal / greater buffers and writing them straight back, so every level visibly regroups the bars in place. The equal block lands in its final position immediately.

Implementation

function stableQuickSort(arr, stats) {
  function sortRange(input) {
    if (input.length <= 1) return input;
    const pivot = input[input.length >> 1];
    const less = [];
    const equal = [];
    const greater = [];
    for (let i = 0; i < input.length; i++) {
      if (input[i] < pivot) less.push(input[i]); else if (input[i] > pivot) greater.push(input[i]); else equal.push(input[i]);
    }
    return sortRange(less).concat(equal, sortRange(greater));
  }
  const out = sortRange(arr.slice());
  for (let i = 0; i < out.length; i++) {
    arr[i] = out[i];
    write(i, arr[i]);
  }
}