Skip to content

Commit c789b2f

Browse files
committed
sorts: type shrink shell sort for comparable items
1 parent 7428666 commit c789b2f

2 files changed

Lines changed: 18 additions & 1 deletion

File tree

sorts/shrink_shell_sort.py

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,8 +20,14 @@
2020
using a smaller gap, the list is sorted more quickly.
2121
"""
2222

23+
from typing import Protocol
2324

24-
def shell_sort(collection: list) -> list:
25+
26+
class Comparable(Protocol):
27+
def __lt__(self, other: object, /) -> bool: ...
28+
29+
30+
def shell_sort[T: Comparable](collection: list[T]) -> list[T]:
2531
"""Implementation of shell sort algorithm in Python
2632
:param collection: Some mutable ordered collection with heterogeneous
2733
comparable items inside
@@ -33,6 +39,14 @@ def shell_sort(collection: list) -> list:
3339
[]
3440
>>> shell_sort([1])
3541
[1]
42+
>>> shell_sort(["pear", "apple", "orange"])
43+
['apple', 'orange', 'pear']
44+
>>> shell_sort([2.5, -1, 0.0])
45+
[-1, 0.0, 2.5]
46+
>>> shell_sort([1, "a"]) # doctest: +IGNORE_EXCEPTION_DETAIL
47+
Traceback (most recent call last):
48+
...
49+
TypeError: ...
3650
"""
3751

3852
# Choose an initial gap value

tests/test_sorts.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@
3737
from sorts.quick_sort import quick_sort
3838
from sorts.selection_sort import selection_sort
3939
from sorts.shell_sort import shell_sort
40+
from sorts.shrink_shell_sort import shell_sort as shrink_shell_sort
4041
from sorts.stooge_sort import stooge_sort
4142
from sorts.strand_sort import strand_sort
4243

@@ -68,6 +69,7 @@ def test_heap_sort() -> None:
6869
quick_sort,
6970
selection_sort,
7071
shell_sort,
72+
shrink_shell_sort,
7173
stooge_sort,
7274
strand_sort,
7375
)
@@ -122,6 +124,7 @@ def test_sort_matches_builtin(sort, case) -> None:
122124
insertion_sort,
123125
merge_sort,
124126
selection_sort,
127+
shrink_shell_sort,
125128
],
126129
ids=lambda f: f.__name__,
127130
)

0 commit comments

Comments
 (0)