Bucket Sort with Python

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))

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值