Skip to content

Commit 73455e6

Browse files
Merge pull request geekcomputers#1063 from mohd-mehraj/patch-6
Shell Sort
2 parents 157e95b + 2870985 commit 73455e6

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

Sorting Algorithims/Shell Sort

+47
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
# Python program for implementation of Shell Sort
2+
3+
def shellSort(arr):
4+
5+
# Start with a big gap, then reduce the gap
6+
n = len(arr)
7+
gap = n/2
8+
9+
# Do a gapped insertion sort for this gap size.
10+
# The first gap elements a[0..gap-1] are already in gapped
11+
# order keep adding one more element until the entire array
12+
# is gap sorted
13+
while gap > 0:
14+
15+
for i in range(gap,n):
16+
17+
# add a[i] to the elements that have been gap sorted
18+
# save a[i] in temp and make a hole at position i
19+
temp = arr[i]
20+
21+
# shift earlier gap-sorted elements up until the correct
22+
# location for a[i] is found
23+
j = i
24+
while j >= gap and arr[j-gap] >temp:
25+
arr[j] = arr[j-gap]
26+
j -= gap
27+
28+
# put temp (the original a[i]) in its correct location
29+
arr[j] = temp
30+
gap /= 2
31+
32+
33+
# Driver code to test above
34+
arr = [ 12, 34, 54, 2, 3]
35+
36+
n = len(arr)
37+
print ("Array before sorting:")
38+
for i in range(n):
39+
print(arr[i]),
40+
41+
shellSort(arr)
42+
43+
print ("\nArray after sorting:")
44+
for i in range(n):
45+
print(arr[i]),
46+
47+
# This code is contributed by mohd-mehraj

0 commit comments

Comments
 (0)