Skip to content

Commit f1cbfd7

Browse files
committed
sorts: make shell_sort work with any Comparable, not just int
Use a Comparable Protocol + TypeVar bound so that shell_sort correctly expresses it can sort any orderable type, not just integers. Adds string and float doctest examples. Part of #15234
1 parent 3f8772c commit f1cbfd7

1 file changed

Lines changed: 22 additions & 4 deletions

File tree

sorts/shell_sort.py

Lines changed: 22 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,28 +2,46 @@
22
https://en.wikipedia.org/wiki/Shellsort#Pseudocode
33
"""
44

5+
from typing import Any, Protocol, TypeVar
6+
7+
8+
class Comparable(Protocol):
9+
def __lt__(self, other: Any, /) -> bool: ...
10+
11+
12+
T = TypeVar("T", bound=Comparable)
13+
14+
15+
def shell_sort(collection: list[T]) -> list[T]:
16+
"""Pure implementation of shell sort algorithm in Python.
517
6-
def shell_sort(collection: list[int]) -> list[int]:
7-
"""Pure implementation of shell sort algorithm in Python
818
:param collection: Some mutable ordered collection with heterogeneous
919
comparable items inside
1020
:return: the same collection ordered by ascending
1121
22+
Examples:
1223
>>> shell_sort([0, 5, 3, 2, 2])
1324
[0, 2, 2, 3, 5]
1425
>>> shell_sort([])
1526
[]
1627
>>> shell_sort([-2, -5, -45])
1728
[-45, -5, -2]
29+
>>> shell_sort(["c", "a", "b"])
30+
['a', 'b', 'c']
31+
>>> shell_sort([2.5, -1.0, 0.0])
32+
[-1.0, 0.0, 2.5]
33+
>>> shell_sort([0, 5, 3, 2, 2]) == sorted([0, 5, 3, 2, 2])
34+
True
35+
>>> shell_sort(["c", "a", "b"]) == sorted(["c", "a", "b"])
36+
True
1837
"""
1938
# Marcin Ciura's gap sequence
20-
2139
gaps = [701, 301, 132, 57, 23, 10, 4, 1]
2240
for gap in gaps:
2341
for i in range(gap, len(collection)):
2442
insert_value = collection[i]
2543
j = i
26-
while j >= gap and collection[j - gap] > insert_value:
44+
while j >= gap and insert_value < collection[j - gap]:
2745
collection[j] = collection[j - gap]
2846
j -= gap
2947
if j != i:

0 commit comments

Comments
 (0)