Comb Sort

Improves on bubble sort by using a gap that shrinks by factor 1.3 each pass. Eliminates turtles (small values near end) much faster.

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

How it works

Improves on bubble sort by using a gap that shrinks by factor 1.3 each pass. Eliminates turtles (small values near end) much faster.

Implementation

function combSort(arr, stats) {
  const n = arr.length;
  let gap = n, shrink = 1.3, done = false;
  while (!done) {
    gap = Math.floor(gap / shrink);
    if (gap <= 1) {
      gap = 1;
      done = true;
    }
    for (let i = 0; i + gap < n; i++) {
      compare(i, i + gap);
      if (arr[i] > arr[i + gap]) {
        [arr[i], arr[i + gap]] = [arr[i + gap], arr[i]];
        swap(i, i + gap);
        done = false;
      }
    }
  }
  for (let i = 0; i < n; i++) markSorted(i);
}