function combSort(array: number[]) {let gap = array.length;
let swapped = true;
while (gap > 1 || swapped) {gap = Math.max(1, Math.floor(gap / 1.3));
swapped = false;
for (let i = 0; i + gap < array.length; i++) { if (array[i] > array[i + gap]) {swap(array, i, i + gap);
swapped = true;
}
}
}
}
Start with gap = 24, the whole array. Comparing far apart first kills the small values stuck at the end.
Understanding Comb sort
The idea
Comb sort is bubble sort where the compared elements start far apart and the gap shrinks by a factor of 1.3 every pass until it reaches 1. Large gaps move small values from the far end to the front in a single swap, which is exactly what bubble sort cannot do.
By the time the gap is 1 the array is nearly sorted and the final bubble passes barely swap anything. The factor 1.3 comes from experiment: smaller factors do too many passes, larger ones leave too much for the end.
The four stages
Complexity
Versus its siblings
Pseudocode
COMBSORT(array)
gap ← n; swapped ← true
while gap > 1 or swapped
gap ← max(1, ⌊gap / 1.3⌋); swapped ← false
for i ← 0 while i + gap < n: if array[i] > array[i + gap]: swap them; swapped ← true
When to use
Pitfalls
History
Włodzimierz Dobosiewicz published the idea in 1980; Stephen Lacey and Richard Box rediscovered it in 1991 and named it comb sort in a Byte magazine article, where they found the 1.3 shrink factor by simulation. It is Shell sort's idea applied to bubble sort instead of insertion sort.