Skip to content

Commit da4680b

Browse files
sorts: type cocktail shaker sort for comparable items
1 parent 927c7d3 commit da4680b

2 files changed

Lines changed: 14 additions & 2 deletions

File tree

sorts/cocktail_shaker_sort.py

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,14 @@
44
https://en.wikipedia.org/wiki/Cocktail_shaker_sort
55
"""
66

7+
from typing import Protocol
78

8-
def cocktail_shaker_sort(arr: list[int]) -> list[int]:
9+
10+
class Comparable(Protocol):
11+
def __lt__(self, other: object, /) -> bool: ...
12+
13+
14+
def cocktail_shaker_sort[T: Comparable](arr: list[T]) -> list[T]:
915
"""
1016
Sorts a list using the Cocktail Shaker Sort algorithm.
1117
@@ -28,7 +34,12 @@ def cocktail_shaker_sort(arr: list[int]) -> list[int]:
2834
Traceback (most recent call last):
2935
...
3036
TypeError: 'tuple' object does not support item assignment
31-
"""
37+
38+
>>> cocktail_shaker_sort(["elderberry", "banana", "date", "apple", "cherry"])
39+
['apple', 'banana', 'cherry', 'date', 'elderberry']
40+
>>> cocktail_shaker_sort([3.2, -1.1, 2.4, 0.5])
41+
[-1.1, 0.5, 2.4, 3.2]
42+
"""
3243
start, end = 0, len(arr) - 1
3344

3445
while start < end:

tests/test_sorts.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -96,6 +96,7 @@ def test_sort_matches_builtin(sort, case):
9696
bubble_sort_iterative,
9797
bubble_sort_recursive,
9898
insertion_sort,
99+
cocktail_shaker_sort,
99100
],
100101
ids=lambda f: f.__name__,
101102
)

0 commit comments

Comments
 (0)