# Python: Sort a list of elements using Comb sort

## Python Search and Sorting : Exercise-15 with Solution

Write a Python program to sort a list of elements using Comb sort.

The Comb Sort is a variant of the Bubble Sort. Like the Shell sort, the Comb Sort increases the gap used in comparisons and exchanges. Some implementations use the insertion sort once the gap is less than a certain amount. The basic idea is to eliminate turtles, or small values near the end of the list, since in a bubble sort these slow the sorting down tremendously. Rabbits, large values around the beginning of the list do not pose a problem in bubble sort.
In bubble sort, when any two elements are compared, they always have a gap of 1. The basic idea of comb sort is that the gap can be much more than 1.

**Visualization of comb sort:**

Animation credits : Jerejesse

**Sample Solution**:

**Python Code:**

```
def comb_sort(nums):
shrink_fact = 1.3
gaps = len(nums)
swapped = True
i = 0
while gaps > 1 or swapped:
gaps = int(float(gaps) / shrink_fact)
swapped = False
i = 0
while gaps + i < len(nums):
if nums[i] > nums[i+gaps]:
nums[i], nums[i+gaps] = nums[i+gaps], nums[i]
swapped = True
i += 1
return nums
num1 = input('Input comma separated numbers:\n').strip()
nums = [int(item) for item in num1.split(',')]
print(comb_sort(nums))
```

Sample Output:

Input comma separated numbers: 5, 15, 37, 25, 79 [5, 15, 25, 37, 79]

**Flowchart: **

**Python Code Editor:**

** Contribute your code and comments through Disqus.**

**Previous:** Write a Python program to sort a list of elements using Cocktail shaker sort.

**Next:** Write a Python program to sort a list of elements using Cycle sort.

**What is the difficulty level of this exercise?**

Test your Programming skills with w3resource's quiz.

## Python: Tips of the Day

**Use Reversed() In for Loops:**

>>> tasks = ['laundry', 'picking up kids', 'gardening', 'cooking'] >>> for task in reversed(tasks): ... print(task) ... cooking gardening picking up kids laundry

**Exercises: Weekly Top 12 Most Popular Topics**- Pandas DataFrame: Exercises, Practice, Solution
- Conversion Tools
- JavaScript: HTML Form Validation
- SQL Exercises, Practice, Solution - SUBQUERIES
- C Programming Exercises, Practice, Solution : For Loop
- Python Exercises, Practice, Solution
- Python Data Type: List - Exercises, Practice, Solution
- C++ Basic: Exercises, Practice, Solution
- SQL Exercises, Practice, Solution - exercises on Employee Database
- SQL Exercises, Practice, Solution - exercises on Movie Database
- SQL Exercises, Practice, Solution - exercises on Soccer Database
- C Programming Exercises, Practice, Solution : Recursion