From 6435da530ec38d61684b930a3a8264a10821f8c5 Mon Sep 17 00:00:00 2001 From: Gavin-Yau <2695188238@qq.com> Date: Fri, 11 Sep 2026 18:15:47 +0800 Subject: [PATCH] sorts: type cocktail shaker sort for comparable items --- sorts/cocktail_shaker_sort.py | 12 +++++++++++- tests/test_sorts.py | 1 + 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/sorts/cocktail_shaker_sort.py b/sorts/cocktail_shaker_sort.py index de126426d986..e802336e4321 100644 --- a/sorts/cocktail_shaker_sort.py +++ b/sorts/cocktail_shaker_sort.py @@ -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. @@ -28,6 +34,10 @@ 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([1, "a"]) # doctest: +IGNORE_EXCEPTION_DETAIL + Traceback (most recent call last): + ... + TypeError: ... """ start, end = 0, len(arr) - 1 diff --git a/tests/test_sorts.py b/tests/test_sorts.py index 9bcec1f6b335..799ab5979dff 100644 --- a/tests/test_sorts.py +++ b/tests/test_sorts.py @@ -115,6 +115,7 @@ def test_sort_matches_builtin(sort, case): bubble_sort_iterative, bubble_sort_recursive, circle_sort, + cocktail_shaker_sort, gnome_sort, insertion_sort, merge_sort,