Fix bucket sort (#2494)

* fixed bucket sort

* delete blank line
This commit is contained in:
Du Yuanchao 2020-10-01 08:53:42 +08:00 committed by GitHub
parent ddfa9e4f22
commit 2fa009aa53
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -27,43 +27,41 @@ If k = O(n), time complexity is O(n)
Source: https://en.wikipedia.org/wiki/Bucket_sort 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] >>> data = [-1, 2, -5, 0]
>>> bucket_sort(data) == sorted(data) >>> bucket_sort(data) == sorted(data)
True True
>>> data = [9, 8, 7, 6, -12] >>> data = [9, 8, 7, 6, -12]
>>> bucket_sort(data) == sorted(data) >>> bucket_sort(data) == sorted(data)
True True
>>> data = [.4, 1.2, .1, .2, -.9] >>> data = [.4, 1.2, .1, .2, -.9]
>>> bucket_sort(data) == sorted(data) >>> bucket_sort(data) == sorted(data)
True True
>>> bucket_sort([]) == sorted([])
>>> bucket_sort([]) True
Traceback (most recent call last): >>> import random
... >>> collection = random.sample(range(-50, 50), 50)
Exception: Please add some elements in the array. >>> bucket_sort(collection) == sorted(collection)
True
""" """
if len(my_list) == 0: if len(my_list) == 0:
raise Exception("Please add some elements in the array.") return []
min_value, max_value = min(my_list), max(my_list)
min_value, max_value = (min(my_list), max(my_list)) bucket_count = int(max_value - min_value) + 1
bucket_count = (max_value - min_value) // bucket_size + 1 buckets = [[] for _ in range(bucket_count)]
buckets = [[] for _ in range(int(bucket_count))]
for i in range(len(my_list)): 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( return [v for bucket in buckets for v in sorted(bucket)]
buckets[i][j] for i in range(len(buckets)) for j in range(len(buckets[i]))
)
if __name__ == "__main__": if __name__ == "__main__":
from doctest import testmod
testmod()
assert bucket_sort([4, 5, 3, 2, 1]) == [1, 2, 3, 4, 5] 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] assert bucket_sort([0, 1, -10, 15, 2, -2]) == [-10, -2, 0, 1, 2, 15]