Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update cocktail_shaker_sort.py #10987

Merged
merged 6 commits into from
Oct 26, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 37 additions & 15 deletions sorts/cocktail_shaker_sort.py
Original file line number Diff line number Diff line change
@@ -1,40 +1,62 @@
""" https://en.wikipedia.org/wiki/Cocktail_shaker_sort """
"""
An implementation of the cocktail shaker sort algorithm in pure Python.

https://en.wikipedia.org/wiki/Cocktail_shaker_sort
"""

def cocktail_shaker_sort(unsorted: list) -> list:

def cocktail_shaker_sort(arr: list[int]) -> list[int]:
"""
Pure implementation of the cocktail shaker sort algorithm in Python.
Sorts a list using the Cocktail Shaker Sort algorithm.

:param arr: List of elements to be sorted.
:return: Sorted list.

>>> 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]
>>> 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
"""
for i in range(len(unsorted) - 1, 0, -1):
start, end = 0, len(arr) - 1

while start < end:
swapped = False

for j in range(i, 0, -1):
if unsorted[j] < unsorted[j - 1]:
unsorted[j], unsorted[j - 1] = unsorted[j - 1], unsorted[j]
# 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]
swapped = True

for j in range(i):
if unsorted[j] > unsorted[j + 1]:
unsorted[j], unsorted[j + 1] = unsorted[j + 1], unsorted[j]
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]
swapped = True

if not swapped:
break
return unsorted

start += 1 # Increase the start pointer after each pass

return arr


if __name__ == "__main__":
Expand Down