From da4680bd3117df585985c6e7e5eddb97b43aba54 Mon Sep 17 00:00:00 2001 From: Harsh Raj Singhania <40535627+HarshRajSinghania@users.noreply.github.com> Date: Thu, 10 Sep 2026 00:09:40 +0530 Subject: [PATCH] sorts: type cocktail shaker sort for comparable items --- sorts/cocktail_shaker_sort.py | 15 +++++++++++++-- tests/test_sorts.py | 1 + 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/sorts/cocktail_shaker_sort.py b/sorts/cocktail_shaker_sort.py index de126426d986..d1c426d7ada7 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,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: diff --git a/tests/test_sorts.py b/tests/test_sorts.py index caa4b31cac81..53c6602c3cfc 100644 --- a/tests/test_sorts.py +++ b/tests/test_sorts.py @@ -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__, )