Skip to content

Commit acfd1f0

Browse files
committed
Shell Sort implementation in Python
1 parent 40ce81d commit acfd1f0

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

Programs/P53_ShellSort.py

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
# Author: OMKAR PATHAK
2+
# This program illustrates the shell sort implementation in Python
3+
4+
# According to Wikipedia "Shell sort or Shell's method, is an in-place comparison sort.
5+
# It can be seen as either a generalization of sorting by exchange (bubble sort) or sorting by
6+
# insertion (insertion sort). The method starts by sorting pairs of elements far apart from each other,
7+
# then progressively reducing the gap between elements to be compared. Starting with far apart elements
8+
# can move some out-of-place elements into position faster than a simple nearest neighbor exchange."
9+
10+
# Best Case O(n logn); Average Case O(depends on gap sequence); Worst Case O(n)
11+
12+
def shellSort(myList):
13+
gap = len(myList) // 2
14+
while gap > 0:
15+
for i in range(gap, len(myList)):
16+
currentItem = myList[i]
17+
j = i
18+
while j >= gap and myList[j - gap] > currentItem:
19+
myList[j] = myList[j - gap]
20+
j -= gap
21+
myList[j] = currentItem
22+
gap //= 2
23+
24+
return myList
25+
26+
if __name__ == '__main__':
27+
myList = [12, 23, 4, 5, 3, 2, 12, 81, 56, 95]
28+
print(shellSort(myList))

0 commit comments

Comments
 (0)