Python algorithm learning bucket Sorting algorithm example (block sort)

Source: Internet
Author: User
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))

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.