Skip to content

Commit 26e4320

Browse files
sorts: type cocktail shaker sort for comparable items (#15278)
Co-authored-by: Gavin-Yau <2695188238@qq.com>
1 parent 6fc7a99 commit 26e4320

2 files changed

Lines changed: 12 additions & 1 deletion

File tree

sorts/cocktail_shaker_sort.py

Lines changed: 11 additions & 1 deletion
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,6 +34,10 @@ 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
37+
>>> cocktail_shaker_sort([1, "a"]) # doctest: +IGNORE_EXCEPTION_DETAIL
38+
Traceback (most recent call last):
39+
...
40+
TypeError: ...
3141
"""
3242
start, end = 0, len(arr) - 1
3343

tests/test_sorts.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -115,6 +115,7 @@ def test_sort_matches_builtin(sort, case):
115115
bubble_sort_iterative,
116116
bubble_sort_recursive,
117117
circle_sort,
118+
cocktail_shaker_sort,
118119
gnome_sort,
119120
insertion_sort,
120121
merge_sort,

0 commit comments

Comments
 (0)