2020-06-02 09:51:22 +00:00
|
|
|
""" https://en.wikipedia.org/wiki/Cocktail_shaker_sort """
|
|
|
|
|
|
|
|
|
|
|
|
def cocktail_shaker_sort(unsorted: list) -> list:
|
2016-12-04 15:00:20 +00:00
|
|
|
"""
|
|
|
|
Pure implementation of the cocktail shaker sort algorithm in Python.
|
2020-06-02 09:51:22 +00:00
|
|
|
>>> cocktail_shaker_sort([4, 5, 2, 1, 2])
|
|
|
|
[1, 2, 2, 4, 5]
|
|
|
|
|
|
|
|
>>> cocktail_shaker_sort([-4, 5, 0, 1, 2, 11])
|
|
|
|
[-4, 0, 1, 2, 5, 11]
|
|
|
|
|
|
|
|
>>> cocktail_shaker_sort([0.1, -2.4, 4.4, 2.2])
|
|
|
|
[-2.4, 0.1, 2.2, 4.4]
|
|
|
|
|
|
|
|
>>> cocktail_shaker_sort([1, 2, 3, 4, 5])
|
|
|
|
[1, 2, 3, 4, 5]
|
|
|
|
|
|
|
|
>>> cocktail_shaker_sort([-4, -5, -24, -7, -11])
|
|
|
|
[-24, -11, -7, -5, -4]
|
2016-12-04 15:00:20 +00:00
|
|
|
"""
|
2019-10-05 05:14:13 +00:00
|
|
|
for i in range(len(unsorted) - 1, 0, -1):
|
2016-12-04 15:00:20 +00:00
|
|
|
swapped = False
|
2019-08-19 13:37:49 +00:00
|
|
|
|
2016-12-04 15:00:20 +00:00
|
|
|
for j in range(i, 0, -1):
|
2019-10-05 05:14:13 +00:00
|
|
|
if unsorted[j] < unsorted[j - 1]:
|
|
|
|
unsorted[j], unsorted[j - 1] = unsorted[j - 1], unsorted[j]
|
2016-12-04 15:00:20 +00:00
|
|
|
swapped = True
|
|
|
|
|
|
|
|
for j in range(i):
|
2019-10-05 05:14:13 +00:00
|
|
|
if unsorted[j] > unsorted[j + 1]:
|
|
|
|
unsorted[j], unsorted[j + 1] = unsorted[j + 1], unsorted[j]
|
2016-12-04 15:00:20 +00:00
|
|
|
swapped = True
|
2019-08-19 13:37:49 +00:00
|
|
|
|
2016-12-04 15:00:20 +00:00
|
|
|
if not swapped:
|
|
|
|
return unsorted
|
2019-08-19 13:37:49 +00:00
|
|
|
|
2019-10-05 05:14:13 +00:00
|
|
|
|
|
|
|
if __name__ == "__main__":
|
2020-06-02 09:51:22 +00:00
|
|
|
import doctest
|
|
|
|
|
|
|
|
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(",")]
|
2020-06-02 09:51:22 +00:00
|
|
|
print(f"{cocktail_shaker_sort(unsorted) = }")
|