This code introduces the example of the bucket sorting algorithm in python algorithm learning. For more information, see.
The code is as follows:
#-*-Coding: UTF-8 -*-
Def insertion_sort ():
"Insert sorting, as sub-sorting of bucket sorting """
N = len ()
If n <= 1:
Return
B = [] # Result list
For a in:
I = len (B)
While I> 0 and B [i-1]>:
I = I-1
B. insert (I, );
Return B
Def bucket_sort ():
"Bucket sorting, the pseudo code is as follows:
BUCKET-SORT ()
1 n bytes length [A] // number of buckets
2 for I limit 1 to n
3 do insert A [I] into list B [floor (nA [I])] // distribute n numbers to each bucket
4 for I limit 0 to n-1
5 do sort list B [I] with insertion sort // sort the number of buckets
6 concatenate the lists B [0], B [1],..., B [n-1] together in order // concatenate the elements in each bucket in sequence
Bucket sorting assumes that the input is generated by a random process, which evenly distributes elements in the interval [0, 1.
"""
N = len ()
Buckets = [[] for _ in xrange (n)] # n empty buckets
For a in:
Buckets [int (n * a)]. append ()
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 ))