Skip to content
Closed
Show file tree
Hide file tree
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
15 changes: 13 additions & 2 deletions sorts/cocktail_shaker_sort.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,14 @@
https://en.wikipedia.org/wiki/Cocktail_shaker_sort
"""

from typing import Protocol

def cocktail_shaker_sort(arr: list[int]) -> list[int]:

class Comparable(Protocol):
def __lt__(self, other: object, /) -> bool: ...


def cocktail_shaker_sort[T: Comparable](arr: list[T]) -> list[T]:
"""
Sorts a list using the Cocktail Shaker Sort algorithm.

Expand All @@ -28,7 +34,12 @@ def cocktail_shaker_sort(arr: list[int]) -> list[int]:
Traceback (most recent call last):
...
TypeError: 'tuple' object does not support item assignment
"""

>>> cocktail_shaker_sort(["elderberry", "banana", "date", "apple", "cherry"])
['apple', 'banana', 'cherry', 'date', 'elderberry']
>>> cocktail_shaker_sort([3.2, -1.1, 2.4, 0.5])
[-1.1, 0.5, 2.4, 3.2]
"""
start, end = 0, len(arr) - 1

while start < end:
Expand Down
1 change: 1 addition & 0 deletions tests/test_sorts.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,7 @@ def test_sort_matches_builtin(sort, case):
bubble_sort_iterative,
bubble_sort_recursive,
insertion_sort,
cocktail_shaker_sort,
],
ids=lambda f: f.__name__,
)
Expand Down
Loading