Skip to content

Commit 2fa009a

Browse files
Fix bucket sort (TheAlgorithms#2494)
* fixed bucket sort * delete blank line
1 parent ddfa9e4 commit 2fa009a

File tree

1 file changed

+16
-18
lines changed

1 file changed

+16
-18
lines changed

Diff for: sorts/bucket_sort.py

+16-18
Original file line numberDiff line numberDiff line change
@@ -27,43 +27,41 @@
2727
2828
Source: https://en.wikipedia.org/wiki/Bucket_sort
2929
"""
30-
DEFAULT_BUCKET_SIZE = 5
3130

3231

33-
def bucket_sort(my_list: list, bucket_size: int = DEFAULT_BUCKET_SIZE) -> list:
32+
def bucket_sort(my_list: list) -> list:
3433
"""
3534
>>> data = [-1, 2, -5, 0]
3635
>>> bucket_sort(data) == sorted(data)
3736
True
38-
3937
>>> data = [9, 8, 7, 6, -12]
4038
>>> bucket_sort(data) == sorted(data)
4139
True
42-
4340
>>> data = [.4, 1.2, .1, .2, -.9]
4441
>>> bucket_sort(data) == sorted(data)
4542
True
46-
47-
>>> bucket_sort([])
48-
Traceback (most recent call last):
49-
...
50-
Exception: Please add some elements in the array.
43+
>>> bucket_sort([]) == sorted([])
44+
True
45+
>>> import random
46+
>>> collection = random.sample(range(-50, 50), 50)
47+
>>> bucket_sort(collection) == sorted(collection)
48+
True
5149
"""
5250
if len(my_list) == 0:
53-
raise Exception("Please add some elements in the array.")
54-
55-
min_value, max_value = (min(my_list), max(my_list))
56-
bucket_count = (max_value - min_value) // bucket_size + 1
57-
buckets = [[] for _ in range(int(bucket_count))]
51+
return []
52+
min_value, max_value = min(my_list), max(my_list)
53+
bucket_count = int(max_value - min_value) + 1
54+
buckets = [[] for _ in range(bucket_count)]
5855

5956
for i in range(len(my_list)):
60-
buckets[int((my_list[i] - min_value) // bucket_size)].append(my_list[i])
57+
buckets[(int(my_list[i] - min_value) // bucket_count)].append(my_list[i])
6158

62-
return sorted(
63-
buckets[i][j] for i in range(len(buckets)) for j in range(len(buckets[i]))
64-
)
59+
return [v for bucket in buckets for v in sorted(bucket)]
6560

6661

6762
if __name__ == "__main__":
63+
from doctest import testmod
64+
65+
testmod()
6866
assert bucket_sort([4, 5, 3, 2, 1]) == [1, 2, 3, 4, 5]
6967
assert bucket_sort([0, 1, -10, 15, 2, -2]) == [-10, -2, 0, 1, 2, 15]

0 commit comments

Comments
 (0)