Comb Sort – Python
Last Updated :
26 Feb, 2025
Improve
Comb Sort is an improvement over Bubble Sort, and it aims to eliminate the problem of small values near the end of the list, which causes Bubble Sort to take more time than necessary. Comb Sort uses a larger gap for comparison, which gradually reduces until it becomes 1 (like the gap in Shell Sort). By doing this, it helps in more efficient sorting by “jumping over” some unnecessary comparisons and swaps.
- The shrink factor has been empirically found to be 1.3 (by testing Comb sort on over 200,000 random lists)
- Although it works better than Bubble Sort on average, the worst case remains O(n2).
How does Comb Sort work?
- Start with a large gap: The gap is initially set to the length of the list divided by a factor (usually 1.3). This larger gap allows the algorithm to sort elements that are far apart.
- Compare elements at the gap distance: Elements that are farther apart are compared and swapped if they are in the wrong order.
- Reduce the gap: After each pass, the gap is reduced (usually by dividing by 1.3), and the process repeats until the gap becomes 1, at which point it behaves like a regular Bubble Sort.
- Final pass with gap = 1: Once the gap is 1, the algorithm finishes sorting the list.
def getNextGap(gap):
# Shrink gap by Shrink factor
gap = (gap * 10)/13
if gap < 1:
return 1
return gap
# Function to sort arr[] using Comb Sort
def combSort(arr):
n = len(arr)
# Initialize gap
gap = n
# Initialize swapped as true to make sure that
# loop runs
swapped = True
# Keep running while gap is more than 1 and last
# iteration caused a swap
while gap != 1 or swapped == 1:
# Find next gap
gap = getNextGap(gap)
# Initialize swapped as false so that we can
# check if swap happened or not
swapped = False
# Compare all elements with current gap
for i in range(0, n-gap):
if arr[i] > arr[i + gap]:
arr[i], arr[i + gap] = arr[i + gap], arr[i]
swapped = True
# Driver code
arr = [8, 4, 1, 3, -44, 23, -6, 28, 0]
combSort(arr)
print ("Sorted array:")
for i in range(len(arr)):
print(arr[i]),
Output
Sorted array: -44 -6 0 1 3 4 8 23 28
Time Complexity: The worst-case complexity of this algorithm is O(n2).
Auxiliary Space: O(1).
Please refer complete article on Comb Sort for more details!