Fix list index in bucket_sort.py

This commit is contained in:
Tianyi Zheng 2023-08-17 18:32:40 -07:00 committed by GitHub
parent ce9a8e8484
commit 5ab1cccc39
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -55,11 +55,13 @@ def bucket_sort(my_list: list, bucket_count: int = 10) -> list:
if len(my_list) == 0 or bucket_count <= 0:
return []
min_value = min(my_list)
min_value, max_value = min(my_list), max(my_list)
bucket_size = (max_value - min_value) / bucket_count
buckets: list[list] = [[] for _ in range(bucket_count)]
for val in my_list:
buckets[int(val - min_value)].append(val)
index = min(int((val - min_value) / bucket_size), bucket_count - 1)
buckets[index].append(val)
return [val for bucket in buckets for val in sorted(bucket)]