Comb Sort, explained step by step
Comb Sort improves Bubble Sort by comparing elements a gap apart. The gap starts at the array length and shrinks by a factor of about 1.3 each pass, quickly moving small values from the end towards the front before finishing with ordinary adjacent swaps.
Intuition: Comb tangled hair with a wide-tooth comb first, then progressively finer combs.
How it works
- Start with gap = n.
- Shrink the gap by 1.3 (minimum 1).
- Compare and swap every pair that is gap apart.
- Repeat until the gap is 1 and a full pass makes no swaps.
Complexity
- Best: O(n log n)
- Average: O(n² / 2ᵖ)
- Worst: O(n²)
- Space: O(1)
- Stable: no
When to use it
A simple, low-memory improvement over Bubble Sort for small-to-medium arrays.
Interview questions
- Why does a shrink factor of ~1.3 work well?
- Why is Comb Sort not stable?