From 2fa009aa530ee1c243090c31b69bbf7effc754e2 Mon Sep 17 00:00:00 2001 From: Du Yuanchao Date: Thu, 1 Oct 2020 08:53:42 +0800 Subject: [PATCH] Fix bucket sort (#2494) * fixed bucket sort * delete blank line --- sorts/bucket_sort.py | 34 ++++++++++++++++------------------ 1 file changed, 16 insertions(+), 18 deletions(-) diff --git a/sorts/bucket_sort.py b/sorts/bucket_sort.py index 178b4f664..a0566be66 100644 --- a/sorts/bucket_sort.py +++ b/sorts/bucket_sort.py @@ -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]