Skip to content

Commit f76f948

Browse files
committed
Shell Sort
1 parent 6deb75b commit f76f948

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed

DSA-Python/Algorithms/ShellSort.py

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
"""
2+
Shell Sort
3+
Shell sort is an optimization over Insertion sort
4+
Aim is to reduce swaps and comparisons by swapping greater elements at right side of array and light element at left
5+
Algorithm
6+
Start with gap = n/2 and sort sub arrays
7+
Keep reducing gap by n/2 and keep on sorting sub arrays
8+
Last iteration should have gap = 1. At this point it is same as insertion sort
9+
Actually, we are doing insertion sort but with some optimization
10+
so that number of swaps and comparisons can be reduced
11+
Disadvantage of Insertion sort over Shell Sort
12+
When small elements are towards the end of array it takes many:
13+
Comparisons
14+
Swaps
15+
Worst-case Performance
16+
O(n^2) (worst known worst-case gap sequence)
17+
O(n log^2(n)) (best known worst-case gap sequence)
18+
Best-case Performance
19+
O(n log n) (most gap sequences)
20+
O(n log^2(n)) (best known worst-case gap sequence)
21+
22+
"""
23+
24+
def ShellSort(arr):
25+
# gap = 3 # initialised gap to 3
26+
size = len(arr)
27+
gap = size // 2 # initialised gap to half of size of array
28+
while gap > 0:
29+
for i in range(gap, size):
30+
pointer = arr[i] # pointer initialised to array such that gap is maintained
31+
j = i
32+
# get element which is at gap 3 and compare with current pointer element AND j>=gap else (j-gap) would be negative
33+
while j >= gap and arr[j - gap] > pointer:
34+
arr[j] = arr[j-gap] # swapped elements
35+
j -= gap # In each while loop iteration, reduce by gap for comparison with previous elements
36+
arr[j] = pointer # after while loop ends, all elements have been swapped
37+
# after function end, all heavy values are at right side and light values at left of partially-sorted array
38+
gap = gap // 2 # gap reduced by half
39+
40+
41+
if __name__ == '__main__':
42+
elements = [21, 38, 29, 17, 4, 25, 11, 32, 9]
43+
# Partially sorted array after Shell Sort[11, 4, 9, 17, 32, 25, 21, 38, 29]
44+
ShellSort(elements)
45+
print(elements)
46+
47+
# Test Cases
48+
tests = [
49+
[89, 78, 61, 53, 23, 21, 17, 12, 9, 7, 6, 2, 1], # DESC sorted array
50+
[], # empty array
51+
[1, 5, 8, 9], # sorted array
52+
[234, 3, 1, 56, 34, 12, 9, 12, 1300], # array with uneven elements
53+
[5] # array with single element
54+
]
55+
56+
for elements in tests:
57+
ShellSort(elements)
58+
print(elements)

0 commit comments

Comments
 (0)