Skip to content

Commit 0e2383a

Browse files
authored
Merge pull request #560 from sravanyabendi/shell-sort-python
Implementation of Shell Sort in Python
2 parents a51c8c5 + 5f614e1 commit 0e2383a

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

Sorting Algorithms/shell_sort.py

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
#function to implement the shell sort
2+
def shellsort(arr,n):
3+
4+
#calculate gap which is half of the length
5+
gap=n//2
6+
7+
# Do a gapped insertion sort for this gap size.
8+
# The first gap elements a[0..gap-1] are already in gapped
9+
# order keep adding one more element until the entire array
10+
# is gap sorted
11+
while(gap>0):
12+
13+
#Loop iterating from gap to n-1
14+
for i in range(gap,n):
15+
temp=arr[i] #value in arr[i] is assigned to temporary variable
16+
j=i
17+
18+
while j>=gap and arr[j-gap]>temp:
19+
arr[j]=arr[j-gap] #value of arr[j-gap] is assigned to arr[j]
20+
j=j-gap
21+
arr[j]=temp #After loop terminates temporary value is assigned to arr[j]
22+
gap=gap//2
23+
24+
25+
26+
n=int(input("Enter the no of elements:"))
27+
arr=list(map(int,input("Enter the elements:").split()))
28+
print("Before Shell Sort")
29+
print(arr)
30+
shellsort(arr,n)
31+
print("After Shell Sort")
32+
print(arr)

0 commit comments

Comments
 (0)