mirror of
https://github.com/TheAlgorithms/Python.git
synced 2024-12-18 01:00:15 +00:00
parent
ddfa9e4f22
commit
2fa009aa53
|
@ -27,43 +27,41 @@ If k = O(n), time complexity is O(n)
|
|||
|
||||
Source: https://en.wikipedia.org/wiki/Bucket_sort
|
||||
"""
|
||||
DEFAULT_BUCKET_SIZE = 5
|
||||
|
||||
|
||||
def bucket_sort(my_list: list, bucket_size: int = DEFAULT_BUCKET_SIZE) -> list:
|
||||
def bucket_sort(my_list: list) -> list:
|
||||
"""
|
||||
>>> data = [-1, 2, -5, 0]
|
||||
>>> bucket_sort(data) == sorted(data)
|
||||
True
|
||||
|
||||
>>> data = [9, 8, 7, 6, -12]
|
||||
>>> bucket_sort(data) == sorted(data)
|
||||
True
|
||||
|
||||
>>> data = [.4, 1.2, .1, .2, -.9]
|
||||
>>> bucket_sort(data) == sorted(data)
|
||||
True
|
||||
|
||||
>>> bucket_sort([])
|
||||
Traceback (most recent call last):
|
||||
...
|
||||
Exception: Please add some elements in the array.
|
||||
>>> bucket_sort([]) == sorted([])
|
||||
True
|
||||
>>> import random
|
||||
>>> collection = random.sample(range(-50, 50), 50)
|
||||
>>> bucket_sort(collection) == sorted(collection)
|
||||
True
|
||||
"""
|
||||
if len(my_list) == 0:
|
||||
raise Exception("Please add some elements in the array.")
|
||||
|
||||
min_value, max_value = (min(my_list), max(my_list))
|
||||
bucket_count = (max_value - min_value) // bucket_size + 1
|
||||
buckets = [[] for _ in range(int(bucket_count))]
|
||||
return []
|
||||
min_value, max_value = min(my_list), max(my_list)
|
||||
bucket_count = int(max_value - min_value) + 1
|
||||
buckets = [[] for _ in range(bucket_count)]
|
||||
|
||||
for i in range(len(my_list)):
|
||||
buckets[int((my_list[i] - min_value) // bucket_size)].append(my_list[i])
|
||||
buckets[(int(my_list[i] - min_value) // bucket_count)].append(my_list[i])
|
||||
|
||||
return sorted(
|
||||
buckets[i][j] for i in range(len(buckets)) for j in range(len(buckets[i]))
|
||||
)
|
||||
return [v for bucket in buckets for v in sorted(bucket)]
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
from doctest import testmod
|
||||
|
||||
testmod()
|
||||
assert bucket_sort([4, 5, 3, 2, 1]) == [1, 2, 3, 4, 5]
|
||||
assert bucket_sort([0, 1, -10, 15, 2, -2]) == [-10, -2, 0, 1, 2, 15]
|
||||
|
|
Loading…
Reference in New Issue
Block a user