1
1
"""
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
11
3
"""
12
4
13
5
@@ -19,26 +11,29 @@ def shell_sort(collection):
19
11
20
12
>>> shell_sort([0, 5, 3, 2, 2])
21
13
[0, 2, 2, 3, 5]
22
-
23
14
>>> shell_sort([])
24
15
[]
25
-
26
16
>>> shell_sort([-2, -5, -45])
27
17
[-45, -5, -2]
28
18
"""
29
19
# Marcin Ciura's gap sequence
30
- gaps = [701 , 301 , 132 , 57 , 23 , 10 , 4 , 1 ]
31
20
21
+ gaps = [701 , 301 , 132 , 57 , 23 , 10 , 4 , 1 ]
32
22
for gap in gaps :
33
23
for i in range (gap , len (collection )):
24
+ insert_value = collection [i ]
34
25
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 ]
37
28
j -= gap
29
+ collection [j ] = insert_value
38
30
return collection
39
31
40
32
41
33
if __name__ == "__main__" :
34
+ from doctest import testmod
35
+
36
+ testmod ()
42
37
user_input = input ("Enter numbers separated by a comma:\n " ).strip ()
43
38
unsorted = [int (item ) for item in user_input .split ("," )]
44
39
print (shell_sort (unsorted ))
0 commit comments