Skip to content

Commit 5fb6b31

Browse files
committedOct 2, 2018
Add comb sort algorithm
1 parent 3a77380 commit 5fb6b31

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed
 

‎sorts/comb_sort.py

+58
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
"""
2+
Comb sort is a relatively simple sorting algorithm originally designed by Wlodzimierz Dobosiewicz in 1980.
3+
Later it was rediscovered by Stephen Lacey and Richard Box in 1991. Comb sort improves on bubble sort.
4+
5+
This is pure python implementation of counting sort algorithm
6+
For doctests run following command:
7+
python -m doctest -v comb_sort.py
8+
or
9+
python3 -m doctest -v comb_sort.py
10+
11+
For manual testing run:
12+
python comb_sort.py
13+
"""
14+
15+
def comb_sort(data):
16+
"""Pure implementation of comb sort algorithm in Python
17+
:param collection: some mutable ordered collection with heterogeneous
18+
comparable items inside
19+
:return: the same collection ordered by ascending
20+
Examples:
21+
>>> comb_sort([0, 5, 3, 2, 2])
22+
[0, 2, 2, 3, 5]
23+
>>> comb_sort([])
24+
[]
25+
>>> comb_sort([-2, -5, -45])
26+
[-45, -5, -2]
27+
"""
28+
shrink_factor = 1.3
29+
gap = len(data)
30+
swapped = True
31+
i = 0
32+
33+
while gap > 1 or swapped:
34+
# Update the gap value for a next comb
35+
gap = int(float(gap) / shrink_factor)
36+
37+
swapped = False
38+
i = 0
39+
40+
while gap + i < len(data):
41+
if data[i] > data[i+gap]:
42+
# Swap values
43+
data[i], data[i+gap] = data[i+gap], data[i]
44+
swapped = True
45+
i += 1
46+
47+
return data
48+
49+
50+
if __name__ == '__main__':
51+
try:
52+
raw_input # Python 2
53+
except NameError:
54+
raw_input = input # Python 3
55+
56+
user_input = raw_input('Enter numbers separated by a comma:\n').strip()
57+
unsorted = [int(item) for item in user_input.split(',')]
58+
print(comb_sort(unsorted))

0 commit comments

Comments
 (0)
Please sign in to comment.