|
2 | 2 | https://en.wikipedia.org/wiki/Shellsort#Pseudocode |
3 | 3 | """ |
4 | 4 |
|
| 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. |
5 | 17 |
|
6 | | -def shell_sort(collection: list[int]) -> list[int]: |
7 | | - """Pure implementation of shell sort algorithm in Python |
8 | 18 | :param collection: Some mutable ordered collection with heterogeneous |
9 | 19 | comparable items inside |
10 | 20 | :return: the same collection ordered by ascending |
11 | 21 |
|
| 22 | + Examples: |
12 | 23 | >>> shell_sort([0, 5, 3, 2, 2]) |
13 | 24 | [0, 2, 2, 3, 5] |
14 | 25 | >>> shell_sort([]) |
15 | 26 | [] |
16 | 27 | >>> shell_sort([-2, -5, -45]) |
17 | 28 | [-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 |
18 | 37 | """ |
19 | 38 | # Marcin Ciura's gap sequence |
20 | | - |
21 | 39 | gaps = [701, 301, 132, 57, 23, 10, 4, 1] |
22 | 40 | for gap in gaps: |
23 | 41 | for i in range(gap, len(collection)): |
24 | 42 | insert_value = collection[i] |
25 | 43 | j = i |
26 | | - while j >= gap and collection[j - gap] > insert_value: |
| 44 | + while j >= gap and insert_value < collection[j - gap]: |
27 | 45 | collection[j] = collection[j - gap] |
28 | 46 | j -= gap |
29 | 47 | if j != i: |
|
0 commit comments