mirror of
https://github.com/TheAlgorithms/Python.git
synced 2025-02-25 18:38:39 +00:00
Fix sorts/bucket_sort.py
This commit is contained in:
parent
8ac86f2ce5
commit
92e7918923
@ -30,7 +30,7 @@ Source: https://en.wikipedia.org/wiki/Bucket_sort
|
||||
from __future__ import annotations
|
||||
|
||||
|
||||
def bucket_sort(my_list: list) -> list:
|
||||
def bucket_sort(my_list: list, bucket_count: int = 10) -> list:
|
||||
"""
|
||||
>>> data = [-1, 2, -5, 0]
|
||||
>>> bucket_sort(data) == sorted(data)
|
||||
@ -43,19 +43,25 @@ def bucket_sort(my_list: list) -> list:
|
||||
True
|
||||
>>> bucket_sort([]) == sorted([])
|
||||
True
|
||||
>>> data = [-1e10, 1e10]
|
||||
>>> bucket_sort(data) == sorted(data)
|
||||
True
|
||||
>>> import random
|
||||
>>> collection = random.sample(range(-50, 50), 50)
|
||||
>>> bucket_sort(collection) == sorted(collection)
|
||||
True
|
||||
"""
|
||||
if len(my_list) == 0:
|
||||
|
||||
if len(my_list) == 0 or bucket_count <= 0:
|
||||
return []
|
||||
|
||||
min_value, max_value = min(my_list), max(my_list)
|
||||
bucket_count = int(max_value - min_value) + 1
|
||||
bucket_size = (max_value - min_value) / bucket_count
|
||||
buckets: list[list] = [[] for _ in range(bucket_count)]
|
||||
|
||||
for i in range(len(my_list)):
|
||||
buckets[(int(my_list[i] - min_value) // bucket_count)].append(my_list[i])
|
||||
index = min(int((my_list[i] - min_value) / bucket_size), bucket_count - 1)
|
||||
buckets[index].append(my_list[i])
|
||||
|
||||
return [v for bucket in buckets for v in sorted(bucket)]
|
||||
|
||||
|
Loading…
x
Reference in New Issue
Block a user