桶排序核心思想:桶排序主要就是将一些数放在一个数组中,每个数对应的是数组下标,刚开始将数组里的每一个元素初始化为0,以后一个数只要出现一次,对应的数组下标里的值就自加1,最后将出现过的数打印输出即可。
DEFAULT_BUCKET_SIZE = 5
def bucket_sort(my_list, bucket_size=DEFAULT_BUCKET_SIZE):
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))]
for i in range(len(my_list)):
buckets[int((my_list[i] - min_value) // bucket_size)].append(my_list[i])
return sorted(
[buckets[i][j] for i in range(len(buckets)) for j in range(len(buckets[i]))]
)
if __name__ == "__main__":
user_input = input("Enter numbers separated by a comma:").strip()
unsorted = [float(n) for n in user_input.split(",") if len(user_input) > 0]
print(bucket_sort(unsorted))