2018-10-02 02:43:25 +00:00
|
|
|
"""
|
2020-03-04 12:40:28 +00:00
|
|
|
This is pure Python implementation of comb sort algorithm.
|
2018-10-02 02:43:25 +00:00
|
|
|
Comb sort is a relatively simple sorting algorithm originally designed by Wlodzimierz Dobosiewicz in 1980.
|
2020-03-04 12:40:28 +00:00
|
|
|
It was rediscovered by Stephen Lacey and Richard Box in 1991. Comb sort improves on bubble sort algorithm.
|
|
|
|
In bubble sort, 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.
|
|
|
|
|
|
|
|
More info on: https://en.wikipedia.org/wiki/Comb_sort
|
2018-10-02 02:43:25 +00:00
|
|
|
|
|
|
|
For doctests run following command:
|
|
|
|
python -m doctest -v comb_sort.py
|
|
|
|
or
|
|
|
|
python3 -m doctest -v comb_sort.py
|
|
|
|
|
|
|
|
For manual testing run:
|
|
|
|
python comb_sort.py
|
|
|
|
"""
|
|
|
|
|
2019-10-05 05:14:13 +00:00
|
|
|
|
2020-03-04 12:40:28 +00:00
|
|
|
def comb_sort(data: list) -> list:
|
2018-10-02 02:43:25 +00:00
|
|
|
"""Pure implementation of comb sort algorithm in Python
|
2020-03-04 12:40:28 +00:00
|
|
|
:param data: mutable collection with comparable items
|
|
|
|
:return: the same collection in ascending order
|
2018-10-02 02:43:25 +00:00
|
|
|
Examples:
|
|
|
|
>>> comb_sort([0, 5, 3, 2, 2])
|
|
|
|
[0, 2, 2, 3, 5]
|
|
|
|
>>> comb_sort([])
|
|
|
|
[]
|
2020-03-04 12:40:28 +00:00
|
|
|
>>> comb_sort([99, 45, -7, 8, 2, 0, -15, 3])
|
|
|
|
[-15, -7, 0, 2, 3, 8, 45, 99]
|
2018-10-02 02:43:25 +00:00
|
|
|
"""
|
|
|
|
shrink_factor = 1.3
|
|
|
|
gap = len(data)
|
2020-03-04 12:40:28 +00:00
|
|
|
completed = False
|
2018-10-02 02:43:25 +00:00
|
|
|
|
2020-03-04 12:40:28 +00:00
|
|
|
while not completed:
|
2018-10-02 02:43:25 +00:00
|
|
|
|
2020-03-04 12:40:28 +00:00
|
|
|
# Update the gap value for a next comb
|
|
|
|
gap = int(gap / shrink_factor)
|
|
|
|
if gap <= 1:
|
|
|
|
completed = True
|
2018-10-02 02:43:25 +00:00
|
|
|
|
2020-03-04 12:40:28 +00:00
|
|
|
index = 0
|
|
|
|
while index + gap < len(data):
|
|
|
|
if data[index] > data[index + gap]:
|
2018-10-02 02:46:47 +00:00
|
|
|
# Swap values
|
2020-03-04 12:40:28 +00:00
|
|
|
data[index], data[index + gap] = data[index + gap], data[index]
|
|
|
|
completed = False
|
|
|
|
index += 1
|
2018-10-02 02:43:25 +00:00
|
|
|
|
|
|
|
return data
|
|
|
|
|
|
|
|
|
2019-10-05 05:14:13 +00:00
|
|
|
if __name__ == "__main__":
|
2020-03-04 12:40:28 +00:00
|
|
|
import doctest
|
2020-03-13 08:23:38 +00:00
|
|
|
|
2020-03-04 12:40:28 +00:00
|
|
|
doctest.testmod()
|
|
|
|
|
2019-10-05 05:14:13 +00:00
|
|
|
user_input = input("Enter numbers separated by a comma:\n").strip()
|
|
|
|
unsorted = [int(item) for item in user_input.split(",")]
|
2018-10-02 02:43:25 +00:00
|
|
|
print(comb_sort(unsorted))
|