Python algorithm learning bucket Sort algorithm instance (block sort) _python

Source: Internet
Author: User

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))

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.