Skip to content

Commit 92fa11b

Browse files
authored
sorts: make shell_sort work with any Comparable, not just int (#15326)
* 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 * fix: use PEP 695 type params, remove TypeVar import
1 parent 032afb5 commit 92fa11b

1 file changed

Lines changed: 19 additions & 4 deletions

File tree

‎sorts/shell_sort.py‎

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

5+
from typing import Any, Protocol
6+
7+
8+
class Comparable(Protocol):
9+
def __lt__(self, other: Any, /) -> bool: ...
10+
11+
12+
def shell_sort[T: Comparable](collection: list[T]) -> list[T]:
13+
"""Pure implementation of shell sort algorithm in Python.
514
6-
def shell_sort(collection: list[int]) -> list[int]:
7-
"""Pure implementation of shell sort algorithm in Python
815
:param collection: Some mutable ordered collection with heterogeneous
916
comparable items inside
1017
:return: the same collection ordered by ascending
1118
19+
Examples:
1220
>>> shell_sort([0, 5, 3, 2, 2])
1321
[0, 2, 2, 3, 5]
1422
>>> shell_sort([])
1523
[]
1624
>>> shell_sort([-2, -5, -45])
1725
[-45, -5, -2]
26+
>>> shell_sort(["c", "a", "b"])
27+
['a', 'b', 'c']
28+
>>> shell_sort([2.5, -1.0, 0.0])
29+
[-1.0, 0.0, 2.5]
30+
>>> shell_sort([0, 5, 3, 2, 2]) == sorted([0, 5, 3, 2, 2])
31+
True
32+
>>> shell_sort(["c", "a", "b"]) == sorted(["c", "a", "b"])
33+
True
1834
"""
1935
# Marcin Ciura's gap sequence
20-
2136
gaps = [701, 301, 132, 57, 23, 10, 4, 1]
2237
for gap in gaps:
2338
for i in range(gap, len(collection)):
2439
insert_value = collection[i]
2540
j = i
26-
while j >= gap and collection[j - gap] > insert_value:
41+
while j >= gap and insert_value < collection[j - gap]:
2742
collection[j] = collection[j - gap]
2843
j -= gap
2944
if j != i:

0 commit comments

Comments
 (0)