Comb Sort is an improvement over Bubble Sort that solves its main problem - small values near the end slowing down the sorting. It works by comparing elements far apart using a gap, which keeps reducing until it becomes 1. This allows faster movement of small elements toward the beginning and large elements toward the end.
How Comb Sort Works
- Initialize the gap: Start with a large gap (usually len(arr) / 1.3), where 1.3 is the shrink factor found experimentally.
- Compare and swap: Compare elements that are gap positions apart and swap if they’re out of order.
- Shrink the gap: Reduce the gap by dividing it by 1.3 each pass until it becomes 1.
- Final pass: When the gap is 1, the algorithm behaves like Bubble Sort to finish sorting.
Python Implementation
Output-44 -6 0 1 3 4 8 23 28
Explanation:
- getNextGap(gap): Shrinks the gap by 1.3 and ensures it doesn’t go below 1.
- combSort(arr): Sorts array using gradually reducing gaps.
- while gap != 1 or swapped: Continues until array is sorted (gap = 1 and no swaps).
- if arr[i] > arr[i + gap]: Swaps out-of-order elements at gap distance.
- combSort(arr) & print(*arr): Sorts and prints the final sorted array.
Related Articles: