Skip to content

Commit e23ff66

Browse files
shell sort (#26)
1 parent 02fe302 commit e23ff66

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

sorts/shell_sort.py

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
"""
2+
https://en.wikipedia.org/wiki/Shellsort
3+
"""
4+
5+
6+
def shell_sort(array):
7+
"""
8+
Shell Sort algorithm
9+
:param array: the array to be sorted.
10+
:return: sorted array.
11+
>>> import random
12+
>>> array = random.sample(range(-50, 50), 100)
13+
>>> shell_sort(array) == sorted(array)
14+
True
15+
>>> import string
16+
>>> array = random.choices(string.ascii_letters + string.digits, k = 100)
17+
>>> shell_sort(array) == sorted(array)
18+
True
19+
>>> array = [random.uniform(-50.0, 50.0) for i in range(100)]
20+
>>> shell_sort(array) == sorted(array)
21+
True
22+
"""
23+
gap = len(array) >> 1
24+
while gap > 0:
25+
for i in range(gap, len(array)):
26+
insert_value = array[i]
27+
j = i - gap
28+
while j >= 0 and insert_value < array[j]:
29+
array[j + gap] = array[j]
30+
j -= gap
31+
array[j + gap] = insert_value
32+
gap >>= 1
33+
return array
34+
35+
36+
if __name__ == "__main__":
37+
from doctest import testmod
38+
39+
testmod()

0 commit comments

Comments
 (0)