最新文章专题视频专题问答1问答10问答100问答1000问答2000关键字专题1关键字专题50关键字专题500关键字专题1500TAG最新视频文章推荐1 推荐3 推荐5 推荐7 推荐9 推荐11 推荐13 推荐15 推荐17 推荐19 推荐21 推荐23 推荐25 推荐27 推荐29 推荐31 推荐33 推荐35 推荐37视频文章20视频文章30视频文章40视频文章50视频文章60 视频文章70视频文章80视频文章90视频文章100视频文章120视频文章140 视频2关键字专题关键字专题tag2tag3文章专题文章专题2文章索引1文章索引2文章索引3文章索引4文章索引5123456789101112131415文章专题3
当前位置: 首页 - 科技 - 知识百科 - 正文

python算法学习之桶排序算法实例(分块排序)

来源:动视网 责编:小采 时间:2020-11-27 14:29:49
文档

python算法学习之桶排序算法实例(分块排序)

python算法学习之桶排序算法实例(分块排序): 代码如下:# -*- coding: utf-8 -*- def insertion_sort(A): 插入排序,作为桶排序的子排序 n = len(A) if n return A B = [] # 结果列表 for a in A: i = len(B) while i > 0 and B[i-1] > a: i =
推荐度:
导读python算法学习之桶排序算法实例(分块排序): 代码如下:# -*- coding: utf-8 -*- def insertion_sort(A): 插入排序,作为桶排序的子排序 n = len(A) if n return A B = [] # 结果列表 for a in A: i = len(B) while i > 0 and B[i-1] > a: i =

代码如下:


# -*- coding: utf-8 -*-

def insertion_sort(A):
"""插入排序,作为桶排序的子排序"""
n = len(A)
if n <= 1:
return A
B = [] # 结果列表
for a in A:
i = len(B)
while i > 0 and B[i-1] > a:
i = i - 1
B.insert(i, a);
return B

def bucket_sort(A):
"""桶排序,伪码如下:
BUCKET-SORT(A)
1 n ← length[A] // 桶数
2 for i ← 1 to n
3 do insert A[i] into list B[floor(nA[i])] // 将n个数分布到各个桶中
4 for i ← 0 to n-1
5 do sort list B[i] with insertion sort // 对各个桶中的数进行排序
6 concatenate the lists B[0],B[1],...,B[n-1] together in order // 依次串联各桶中的元素

桶排序假设输入由一个随机过程产生,该过程将元素均匀地分布在区间[0,1)上。
"""
n = len(A)
buckets = [[] for _ in xrange(n)] # n个空桶
for a in A:
buckets[int(n * a)].append(a)
B = []
for b in buckets:
B.extend(insertion_sort(b))
return B

if __name__ == '__main__':
from random import random
from timeit import Timer

items = [random() for _ in xrange(10000)]

def test_sorted():
print(items)
sorted_items = sorted(items)
print(sorted_items)

def test_bucket_sort():
print(items)
sorted_items = bucket_sort(items)
print(sorted_items)

test_methods = [test_sorted, test_bucket_sort]
for test in test_methods:
name = test.__name__ # test.func_name
t = Timer(name + '()', 'from __main__ import ' + name)
print(name + ' takes time : %f' % t.timeit(1))

文档

python算法学习之桶排序算法实例(分块排序)

python算法学习之桶排序算法实例(分块排序): 代码如下:# -*- coding: utf-8 -*- def insertion_sort(A): 插入排序,作为桶排序的子排序 n = len(A) if n return A B = [] # 结果列表 for a in A: i = len(B) while i > 0 and B[i-1] > a: i =
推荐度:
标签: 排序 python 桶排序
  • 热门焦点

最新推荐

猜你喜欢

热门推荐

专题
Top