Copy CodeThe code is as follows:
#-*-Coding:utf-8-*-
def insertion_sort (A):
"" Insert sort, sub sort as bucket sort "" "
n = Len (A)
If n <= 1:
Return A
B = [] # result 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 as follows:
Bucket-sort (A)
1 N←length[a]//number of barrels
2 for I←1 to n
3 do-insert a[i] into List B[floor (Na[i])//n-number distribution in each bucket
4 for I←0 to N-1
5 do sort list b[i] with insertion sort//sorting the numbers in each bucket
6 concatenate the lists b[0],b[1],..., b[n-1] together in order//concatenation of elements in each bucket sequentially
The bucket ordering assumes that the input is produced by a random process that distributes the elements evenly across the interval [0,1].
"""
n = Len (A)
buckets = [[] for _ in Xrange (n)] # N Empty Buckets
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))