Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Commit 2d209d6

Browse filesBrowse files
cmecklenborgabranhe
authored andcommitted
Adding shell sort
1 parent 813a1ea commit 2d209d6
Copy full SHA for 2d209d6

File tree

Expand file treeCollapse file tree

1 file changed

+35
-0
lines changed
Filter options
Expand file treeCollapse file tree

1 file changed

+35
-0
lines changed

‎sorting/shell_sort.py

Copy file name to clipboard
+35Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
"""This is a Python implementation of the shell sort algorithm
2+
3+
Shell sort is a variation of insertion sort. This method starts by sorting
4+
pairs of elements far away from each other, then progressively reducing the
5+
gap between elements to be compared.
6+
7+
"""
8+
from random import randint
9+
10+
11+
def shell_sort(arr):
12+
13+
n = len(arr)
14+
gap = n//2
15+
16+
while gap > 0:
17+
for i in range(gap, n):
18+
tmp = arr[i]
19+
20+
j = i
21+
while j >= gap and arr[j-gap] > tmp:
22+
arr[j] = arr[j-gap]
23+
j -= gap
24+
arr[j] = tmp
25+
26+
gap //= 2
27+
28+
return arr
29+
30+
31+
# Tests
32+
if __name__ == '__main__':
33+
print(shell_sort([randint(0, 1000) for _ in range(10)]))
34+
print(shell_sort([randint(-500, 500) for _ in range(10)]))
35+

0 commit comments

Comments
0 (0)
Morty Proxy This is a proxified and sanitized view of the page, visit original site.