-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathShell Sort.py
More file actions
30 lines (24 loc) · 766 Bytes
/
Copy pathShell Sort.py
File metadata and controls
30 lines (24 loc) · 766 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
def shell_sort(a):
# Start with a big gap, then reduce the gap
n = len(a)
gap = n // 2
# Do a gapped insertion sort for this gap size.
while gap > 0:
# Perform insertion sort with the current gap
for i in range(gap, n):
# Store the current element in temp
temp = a[i]
# Shift elements that are greater than temp to the right
j = i
while j >= gap and a[j - gap] > temp:
a[j] = a[j - gap]
j -= gap
# Place temp in the correct location
a[j] = temp
# Reduce the gap for the next pass
gap //= 2
return a
# Example usage:
arr = [5, 2, 9, 1, 5, 6]
sorted_arr = shell_sort(arr)
print(sorted_arr)