Bucket Sorted With Python -- 桶排序:
From WiKiPedia:
Bucket sort, or bin sort, is a sorting algorithm that works by distributing the elements of an array into a number of buckets. Each bucket is then sorted individually, either using a different sorting algorithm, or by recursively applying the bucket sorting algorithm. It is a distribution sort, and is a cousin of radix sort in the most to least significant digit flavour. Bucket sort is a generalization of pigeonhole sort. Bucket sort can be implemented with comparisons and therefore can also be considered a comparison sort algorithm. The computational complexity estimates involve the number of buckets.
可以通过该链接可视化理解桶排序的实现过程 https://www.cs.usfca.edu/~galles/visualization/BucketSort.html
摘自博客:
1、bucket sort 桶排序是stable 稳定的
2、桶排序是排序算法中较为快的,比快排还快
3、但是桶排序非常耗运行空间
---------------------------------------------------------
桶排序:
所谓桶排序采用的思想是===>
首先预设置与所要排序数字量相同的空桶;
然后对所要排序数字进行下标处理,具有相同的下标数字有序排在相同下标的空桶中;
最后,将这些有数字的空桶按照从小到大或者从大到小一一提出,就获得有序的数字列。
---------------------------------------------------------------------------------------------------------------------------------
代码如下:
import math
def bucketSort(collection, bucketSize=5):
if len(collection) < 2:
return collection
# 获得需要排序数列的最大值和最小值
minValue = collection[0]
maxValue = collection[0]
for i in range(len(collection)):
if minValue > collection[i]:
minValue = collection[i]
elif maxValue < collection[i]:
maxValue = collection[i]
# 定义桶的容量和初始化桶
bucketCount = math.floor((maxValue-minValue)/bucketSize) + 1
buckets = []
for i in range(0, bucketCount):
buckets.append([])
# 将未排序的数字序列依据下标,提取出来放置于初始化的形同下标的桶中
for i in range(len(collection)):
buckets[math.floor((collection[i]-minValue)/bucketSize)].append(collection[i])
# 拆桶,将每个有数字序列的桶拆开,并按照所需排序顺序添加到空数组中
sorted_collection = []
for i in range(len(buckets)):
for elem in sorted(buckets[i]):
sorted_collection.append(elem)
return sorted_collection
if __name__ == "__main__":
user_input = input('Enter numbers separated by a comma: ').strip()
unsorted = [int(elem) for elem in user_input.split(',')]
print(bucketSort(unsorted))