Skip to content

Commit 0df7827

Browse files
authored
Added Shell Sort in Python div-bargali#255
Added Shell Sort in Python
2 parents 7d327a0 + 3b8576e commit 0df7827

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
# Python program for implementation of Shell Sort
2+
3+
# Shell sort is an algorithm that first sorts the elements far apart
4+
# from each other and successively reduces the interval
5+
# between the elements to be sorted. It is a generalized version of insertion sort.'''
6+
7+
def shellSort(values):
8+
9+
# Start with a somewhat big gap, then reduce the gap
10+
n = len(values)
11+
gap = n//2
12+
13+
# Do a gapped insertion sort for this gap size.
14+
# The first gap elements are already in gapped
15+
# order keep adding one more element until the entire array
16+
# is gap sorted
17+
while gap > 0:
18+
19+
for i in range(gap,n):
20+
21+
# add a[i] to the elements that have been gap sorted
22+
# save a[i] in temp and make a hole at position i
23+
temp = values[i]
24+
25+
# shift earlier gap-sorted elements up until the correct
26+
# location if a[i] is found
27+
j = i
28+
while j >= gap and values[j-gap] >temp:
29+
values[j] = values[j-gap]
30+
j -= gap
31+
32+
# put temporary variable in its correct location
33+
values[j] = temp
34+
gap //= 2
35+
36+
37+
# Insert Test Values
38+
values = [1, 2, 4, 12, 34, 54, 2, 3, 9, 15, 20]
39+
n = len(values)
40+
41+
print ("Array before sorting: "+ str(values))
42+
43+
shellSort(values)
44+
45+
print ("Array after sorting:"+ str(values))
46+

0 commit comments

Comments
 (0)