Open In App

Comb Sort – Python

Last Updated : 26 Feb, 2025
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

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?

  1. 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.
  2. Compare elements at the gap distance: Elements that are farther apart are compared and swapped if they are in the wrong order.
  3. 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.
  4. 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!


Next Article

Similar Reads

three90RightbarBannerImg