Skip to content

Commit 53c2134

Browse files
authored
Refactor shell_sort to use Comparable protocol
Refactor shell_sort function to use a Comparable protocol for type hinting. Update sorting logic to improve clarity.
1 parent 22770e5 commit 53c2134

1 file changed

Lines changed: 34 additions & 9 deletions

File tree

‎sorts/shell_sort.py‎

Lines changed: 34 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,31 +1,56 @@
11
"""
2+
https://en.wikipedia.org/wiki/Shellsort
23
https://en.wikipedia.org/wiki/Shellsort#Pseudocode
34
"""
45

6+
from typing import Any, Protocol
7+
8+
9+
class Comparable(Protocol):
10+
def __lt__(self, other: Any, /) -> bool: ...
511

6-
def shell_sort(collection: list[int]) -> list[int]:
7-
"""
8-
Sort a list of integers using the Shell Sort algorithm.
912

10-
Reference:
11-
https://en.wikipedia.org/wiki/Shellsort
13+
def shell_sort[T: Comparable](collection: list[T]) -> list[T]:
14+
"""Pure implementation of shell sort algorithm in Python.
1215
16+
:param collection: Some mutable ordered collection with heterogeneous
17+
comparable items inside
18+
:return: the same collection ordered in ascending order
19+
20+
Examples:
1321
>>> shell_sort([0, 5, 3, 2, 2])
1422
[0, 2, 2, 3, 5]
1523
>>> shell_sort([])
1624
[]
1725
>>> shell_sort([-2, -5, -45])
1826
[-45, -5, -2]
27+
>>> shell_sort(["c", "a", "b"])
28+
['a', 'b', 'c']
29+
>>> shell_sort([2.5, -1.0, 0.0])
30+
[-1.0, 0.0, 2.5]
31+
>>> shell_sort([0, 5, 3, 2, 2]) == sorted([0, 5, 3, 2, 2])
32+
True
33+
>>> shell_sort(["c", "a", "b"]) == sorted(["c", "a", "b"])
34+
True
1935
"""
36+
# Marcin Ciura's gap sequence
2037
gaps = [701, 301, 132, 57, 23, 10, 4, 1]
21-
2238
for gap in gaps:
2339
for i in range(gap, len(collection)):
2440
insert_value = collection[i]
2541
j = i
26-
while j >= gap and collection[j - gap] > insert_value:
42+
while j >= gap and insert_value < collection[j - gap]:
2743
collection[j] = collection[j - gap]
2844
j -= gap
29-
collection[j] = insert_value
30-
45+
if j != i:
46+
collection[j] = insert_value
3147
return collection
48+
49+
50+
if __name__ == "__main__":
51+
from doctest import testmod
52+
53+
testmod()
54+
user_input = input("Enter numbers separated by a comma:\n").strip()
55+
unsorted = [int(item) for item in user_input.split(",")]
56+
print(shell_sort(unsorted))

0 commit comments

Comments
 (0)