Skip to content

Commit b39f4e5

Browse files
geon0325goswami-rahul
authored andcommitted
added bucket_sort.py & shell_sort.py (keon#296)
* Create bucket_sort.py * Create shell_sort.py * Update test_sort.py * Update __init__.py
1 parent 91aee95 commit b39f4e5

File tree

4 files changed

+63
-1
lines changed

4 files changed

+63
-1
lines changed

algorithms/sort/__init__.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,3 +6,5 @@
66
from .merge_sort import *
77
from .quick_sort import *
88
from .selection_sort import *
9+
from .bucket_sort import *
10+
from .shell_sort import *

algorithms/sort/bucket_sort.py

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
def bucket_sort(arr):
2+
''' Bucket Sort
3+
Complexity: O(n^2)
4+
The complexity is dominated by nextSort
5+
'''
6+
# The number of buckets and make buckets
7+
num_buckets = len(arr)
8+
buckets = [[] for bucket in range(num_buckets)]
9+
# Assign values into bucket_sort
10+
for value in arr:
11+
index = value * num_buckets // (max(arr) + 1)
12+
buckets[index].append(value)
13+
# Sort
14+
sorted_list = []
15+
for i in range(num_buckets):
16+
sorted_list.extend(next_sort(buckets[i]))
17+
return sorted_list
18+
19+
def next_sort(arr):
20+
# We will use insertion sort here.
21+
for i in range(1, len(arr)):
22+
j = i - 1
23+
key = arr[i]
24+
while arr[j] > key and j >= 0:
25+
arr[j+1] = arr[j]
26+
j = j - 1
27+
arr[j + 1] = key
28+
return arr

algorithms/sort/shell_sort.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
def shell_sort(arr):
2+
''' Shell Sort
3+
Complexity: O(n^2)
4+
'''
5+
n = len(arr)
6+
# Initialize size of the gap
7+
gap = n//2
8+
9+
while gap > 0:
10+
y_index = gap
11+
while y_index < len(arr):
12+
y = arr[y_index]
13+
x_index = y_index - gap
14+
while x_index >= 0 and y < arr[x_index]:
15+
arr[x_index + gap] = arr[x_index]
16+
x_index = x_index - gap
17+
arr[x_index + gap] = y
18+
y_index = y_index + 1
19+
gap = gap//2
20+
21+
return arr

tests/test_sort.py

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,9 @@
66
insertion_sort,
77
merge_sort,
88
quick_sort,
9-
selection_sort
9+
selection_sort,
10+
bucket_sort,
11+
shell_sort
1012
)
1113

1214
import unittest
@@ -49,6 +51,15 @@ def test_selection_sort(self):
4951
self.assertEqual([1, 5, 23, 57, 65, 1232],
5052
selection_sort([1, 5, 65, 23, 57, 1232]))
5153

54+
def test_bucket_sort(self):
55+
self.assertEqual([1, 5, 23, 57, 65, 1232],
56+
bucket_sort([1, 5, 65, 23, 57, 1232]))
57+
58+
def test_shell_sort(self):
59+
self.assertEqual([1, 5, 23, 57, 65, 1232],
60+
shell_sort([1, 5, 65, 23, 57, 1232]))
61+
62+
5263

5364
if __name__ == "__main__":
5465
unittest.main()

0 commit comments

Comments
 (0)