2023-10-26 12:27:31 +00:00
|
|
|
"""
|
|
|
|
An implementation of the cocktail shaker sort algorithm in pure Python.
|
2020-06-02 09:51:22 +00:00
|
|
|
|
2023-10-26 12:27:31 +00:00
|
|
|
https://en.wikipedia.org/wiki/Cocktail_shaker_sort
|
|
|
|
"""
|
2020-06-02 09:51:22 +00:00
|
|
|
|
2023-10-26 12:27:31 +00:00
|
|
|
|
|
|
|
def cocktail_shaker_sort(arr: list[int]) -> list[int]:
|
2016-12-04 15:00:20 +00:00
|
|
|
"""
|
2023-10-26 12:27:31 +00:00
|
|
|
Sorts a list using the Cocktail Shaker Sort algorithm.
|
|
|
|
|
|
|
|
:param arr: List of elements to be sorted.
|
|
|
|
:return: Sorted list.
|
|
|
|
|
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]
|
2023-10-26 12:27:31 +00:00
|
|
|
>>> cocktail_shaker_sort(["elderberry", "banana", "date", "apple", "cherry"])
|
|
|
|
['apple', 'banana', 'cherry', 'date', 'elderberry']
|
|
|
|
>>> cocktail_shaker_sort((-4, -5, -24, -7, -11))
|
|
|
|
Traceback (most recent call last):
|
|
|
|
...
|
|
|
|
TypeError: 'tuple' object does not support item assignment
|
2016-12-04 15:00:20 +00:00
|
|
|
"""
|
2023-10-26 12:27:31 +00:00
|
|
|
start, end = 0, len(arr) - 1
|
|
|
|
|
|
|
|
while start < end:
|
2016-12-04 15:00:20 +00:00
|
|
|
swapped = False
|
2019-08-19 13:37:49 +00:00
|
|
|
|
2023-10-26 12:27:31 +00:00
|
|
|
# Pass from left to right
|
|
|
|
for i in range(start, end):
|
|
|
|
if arr[i] > arr[i + 1]:
|
|
|
|
arr[i], arr[i + 1] = arr[i + 1], arr[i]
|
2016-12-04 15:00:20 +00:00
|
|
|
swapped = True
|
|
|
|
|
2023-10-26 12:27:31 +00:00
|
|
|
if not swapped:
|
|
|
|
break
|
|
|
|
|
|
|
|
end -= 1 # Decrease the end pointer after each pass
|
|
|
|
|
|
|
|
# Pass from right to left
|
|
|
|
for i in range(end, start, -1):
|
|
|
|
if arr[i] < arr[i - 1]:
|
|
|
|
arr[i], arr[i - 1] = arr[i - 1], arr[i]
|
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:
|
2021-02-23 09:02:30 +00:00
|
|
|
break
|
2023-10-26 12:27:31 +00:00
|
|
|
|
|
|
|
start += 1 # Increase the start pointer after each pass
|
|
|
|
|
|
|
|
return arr
|
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) = }")
|