Copy Code code as follows:
#-*-Coding:utf-8-*-
def insertion_sort (A):
"", "" "" "" "" "" "" "" "" "" ""
n = Len (A)
If n <= 1:
Return A
B = [] # results list
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, pseudo code is as follows:
Bucket-sort (a)
1 N←length[a]//barrel number
2 for i←1 to n
3 Do insert a[i] into List B[floor (Na[i])//////distribute N to each bucket
4 for i←0 to N-1
&nbs P 5 do sort list b[i] with insertion sort//the number in each bucket
6 concatenate the LIS TS B[0],b[1],..., b[n-1] together in order//sequentially concatenates the elements in each bucket
Bucket sort assumes that input is generated by a random process that distributes elements evenly over the interval [0,1).
"""
n = Len (A)
buckets = [[] for _ in Xrange (n)] # n Empty bucket
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))