From c789b2fdb145d940cbb30803338d1cc969dca5b5 Mon Sep 17 00:00:00 2001 From: taljeon Date: Tue, 15 Sep 2026 05:06:21 +0900 Subject: [PATCH] sorts: type shrink shell sort for comparable items --- sorts/shrink_shell_sort.py | 16 +++++++++++++++- tests/test_sorts.py | 3 +++ 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/sorts/shrink_shell_sort.py b/sorts/shrink_shell_sort.py index f77b73d013a7..f6736364daf1 100644 --- a/sorts/shrink_shell_sort.py +++ b/sorts/shrink_shell_sort.py @@ -20,8 +20,14 @@ using a smaller gap, the list is sorted more quickly. """ +from typing import Protocol -def shell_sort(collection: list) -> list: + +class Comparable(Protocol): + def __lt__(self, other: object, /) -> bool: ... + + +def shell_sort[T: Comparable](collection: list[T]) -> list[T]: """Implementation of shell sort algorithm in Python :param collection: Some mutable ordered collection with heterogeneous comparable items inside @@ -33,6 +39,14 @@ def shell_sort(collection: list) -> list: [] >>> shell_sort([1]) [1] + >>> shell_sort(["pear", "apple", "orange"]) + ['apple', 'orange', 'pear'] + >>> shell_sort([2.5, -1, 0.0]) + [-1, 0.0, 2.5] + >>> shell_sort([1, "a"]) # doctest: +IGNORE_EXCEPTION_DETAIL + Traceback (most recent call last): + ... + TypeError: ... """ # Choose an initial gap value diff --git a/tests/test_sorts.py b/tests/test_sorts.py index 2c9b79aa4bfe..75856cebadb4 100644 --- a/tests/test_sorts.py +++ b/tests/test_sorts.py @@ -37,6 +37,7 @@ from sorts.quick_sort import quick_sort from sorts.selection_sort import selection_sort from sorts.shell_sort import shell_sort +from sorts.shrink_shell_sort import shell_sort as shrink_shell_sort from sorts.stooge_sort import stooge_sort from sorts.strand_sort import strand_sort @@ -68,6 +69,7 @@ def test_heap_sort() -> None: quick_sort, selection_sort, shell_sort, + shrink_shell_sort, stooge_sort, strand_sort, ) @@ -122,6 +124,7 @@ def test_sort_matches_builtin(sort, case) -> None: insertion_sort, merge_sort, selection_sort, + shrink_shell_sort, ], ids=lambda f: f.__name__, )