Comb Sort Algorithm in Python

In this source code example, we will write a code to implement the Comb Sort algorithm in Python.

Comb sort improves on the bubble sort algorithm. In bubble sort, the distance (or gap) between two compared elements is always one. Comb sort improvement is that gap can be much more than 1, in order to prevent slowing down by small values at the end of a list.

Comb Sort Algorithm in Python

In this Python program, we will take input from the User or console and print the result to the output:
def comb_sort(data: list) -> list:
    shrink_factor = 1.3
    gap = len(data)
    completed = False

    while not completed:

        # Update the gap value for a next comb
        gap = int(gap / shrink_factor)
        if gap <= 1:
            completed = True

        index = 0
        while index + gap < len(data):
            if data[index] > data[index + gap]:
                # Swap values
                data[index], data[index + gap] = data[index + gap], data[index]
                completed = False
            index += 1

    return data

if __name__ == "__main__":
    import doctest


    user_input = input("Enter numbers separated by a comma:\n").strip()
    unsorted = [int(item) for item in user_input.split(",")]


Enter numbers separated by a comma:
20, 5, 10, 15, 2, 1
[1, 2, 5, 10, 15, 20]