Python algorithm learning bucket sort algorithm instance of of block sort

  • 2020-04-02 13:17:34
  • OfStack


# -*- coding: utf-8 -*-
def insertion_sort(A):
    """ Insert sort as a subsort of 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  please  length[A] //barrels
    2  for i  please  1 to n
    3    do insert A[i] into list B[floor(nA[i])] //Distribute n Numbers across buckets
    4  for i  please  0 to n-1
    5    do sort list B[i] with insertion sort //Sort the Numbers in each bucket
    6  concatenate the lists B[0],B[1],...,B[n-1] together in order //The elements in each bucket are concatenated in sequence
     Bucket sorting assumes that the input is generated by a random process that distributes the elements evenly over the interval [0,1) On. 
    """
    n = len(A)
    buckets = [[] for _ in xrange(n)] # n An empty barrel 
    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))


Related articles: