Skip to content

Commit 2cd2f99

Browse files
committed
Added shell sort
1 parent 505c524 commit 2cd2f99

File tree

2 files changed

+38
-0
lines changed

2 files changed

+38
-0
lines changed

algorithms/Comparison.py

+3
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
from pigeonholeSort import pigeonhole_sort
1010
from quickSort import quick_sort
1111
from selectionSort import selection_sort
12+
from shellSort import shell_sort
1213

1314
from random import randint
1415

@@ -33,6 +34,8 @@
3334
temp = array[:]
3435
insertion_sort(temp)
3536
temp = array[:]
37+
shell_sort(temp)
38+
temp = array[:]
3639
lsd_radix_sort(temp)
3740
temp = array[:]
3841
pigeonhole_sort(temp)

algorithms/shellSort.py

+35
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
from random import random
2+
3+
4+
def shell_sort(arr):
5+
comparisons = 0
6+
array_accesses = 0
7+
additional_space = 0
8+
n = len(arr)
9+
gap = n // 2
10+
while gap > 0:
11+
for i in range(gap, n):
12+
array_accesses += 1
13+
temp = arr[i]
14+
j = i
15+
while j >= gap and arr[j-gap] > temp:
16+
array_accesses += 2
17+
comparisons += 2
18+
arr[j] = arr[j-gap]
19+
j -= gap
20+
array_accesses += 1
21+
arr[j] = temp
22+
gap //= 2
23+
24+
print("Shell sort:")
25+
print("No. comparisons: " + str(comparisons) +
26+
", no. array accesses: " +
27+
str(array_accesses) + ", no. additional space required: "
28+
+ str(additional_space))
29+
30+
31+
if __name__ == "__main__":
32+
array = []
33+
for i in range(20):
34+
array.append(random())
35+
shell_sort(array)

0 commit comments

Comments
 (0)