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
doctest.testmod()
user_input = input("Enter numbers separated by a comma:\n").strip()
unsorted = [int(item) for item in user_input.split(",")]
print(comb_sort(unsorted))
Output:
Enter numbers separated by a comma:
20, 5, 10, 15, 2, 1
[1, 2, 5, 10, 15, 20]
Related Algorithms in Python
- Write a Python program for Linear Search and Binary Search
- Selection Sort Algorithm in Python
- Bubble Sort Algorithm in Python
- Bogo Sort Algorithm in Python
- Bucket Sort Algorithm in Python
- Comb Sort Algorithm in Python
- Counting Sort Algorithm in Python
- Heap Sort Algorithm in Python
- Insertion Sort Algorithm in Python
- Merge Sort Algorithm in Python
- Quick Sort Algorithm in Python
- Shell Sort Algorithm in Python
- Interpolation Search Algorithm in Python
DSA
Python
Comments
Post a Comment