diff --git a/sorts/shell_sort.py b/sorts/shell_sort.py index b65609c974b7..6bf52c56b3bb 100644 --- a/sorts/shell_sort.py +++ b/sorts/shell_sort.py @@ -2,8 +2,17 @@ https://en.wikipedia.org/wiki/Shellsort#Pseudocode """ +from typing import Any, Protocol, TypeVar -def shell_sort(collection: list[int]) -> list[int]: + +class Comparable(Protocol): + def __lt__(self, other: Any, /) -> bool: ... + + +T = TypeVar("T", bound=Comparable) + + +def shell_sort[T: Comparable](collection: list[T]) -> list[T]: """Pure implementation of shell sort algorithm in Python :param collection: Some mutable ordered collection with heterogeneous comparable items inside @@ -15,9 +24,16 @@ def shell_sort(collection: list[int]) -> list[int]: [] >>> shell_sort([-2, -5, -45]) [-45, -5, -2] + >>> shell_sort(["d", "a", "b", "e", "c"]) + ['a', 'b', 'c', 'd', 'e'] + >>> shell_sort([3, 1.5, 2, 0.5]) + [0.5, 1.5, 2, 3] + >>> shell_sort([1, "two", 3]) + Traceback (most recent call last): + ... + TypeError: '>' not supported between instances of 'int' and 'str' """ # Marcin Ciura's gap sequence - gaps = [701, 301, 132, 57, 23, 10, 4, 1] for gap in gaps: for i in range(gap, len(collection)):