Skip to content

Commit 53371b2

Browse files
Optimization for shell sort (#4038)
* fixed shell sort * udpate code style * Update sorts/shell_sort.py Co-authored-by: John Law <[email protected]> Co-authored-by: John Law <[email protected]>
1 parent ae8a5f8 commit 53371b2

File tree

1 file changed

+9
-14
lines changed

1 file changed

+9
-14
lines changed

Diff for: sorts/shell_sort.py

+9-14
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,5 @@
11
"""
2-
This is a pure Python implementation of the shell sort algorithm
3-
4-
For doctests run following command:
5-
python -m doctest -v shell_sort.py
6-
or
7-
python3 -m doctest -v shell_sort.py
8-
9-
For manual testing run:
10-
python shell_sort.py
2+
https://en.wikipedia.org/wiki/Shellsort#Pseudocode
113
"""
124

135

@@ -19,26 +11,29 @@ def shell_sort(collection):
1911
2012
>>> shell_sort([0, 5, 3, 2, 2])
2113
[0, 2, 2, 3, 5]
22-
2314
>>> shell_sort([])
2415
[]
25-
2616
>>> shell_sort([-2, -5, -45])
2717
[-45, -5, -2]
2818
"""
2919
# Marcin Ciura's gap sequence
30-
gaps = [701, 301, 132, 57, 23, 10, 4, 1]
3120

21+
gaps = [701, 301, 132, 57, 23, 10, 4, 1]
3222
for gap in gaps:
3323
for i in range(gap, len(collection)):
24+
insert_value = collection[i]
3425
j = i
35-
while j >= gap and collection[j] < collection[j - gap]:
36-
collection[j], collection[j - gap] = collection[j - gap], collection[j]
26+
while j >= gap and collection[j - gap] > insert_value:
27+
collection[j] = collection[j - gap]
3728
j -= gap
29+
collection[j] = insert_value
3830
return collection
3931

4032

4133
if __name__ == "__main__":
34+
from doctest import testmod
35+
36+
testmod()
4237
user_input = input("Enter numbers separated by a comma:\n").strip()
4338
unsorted = [int(item) for item in user_input.split(",")]
4439
print(shell_sort(unsorted))

0 commit comments

Comments
 (0)