欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

python算法學(xué)習(xí)之桶排序算法實(shí)例(分塊排序)

 更新時(shí)間:2013年12月18日 10:02:16   作者:  
本代碼介紹了python算法學(xué)習(xí)中的桶排序算法實(shí)例,大家參考使用吧

復(fù)制代碼 代碼如下:

# -*- coding: utf-8 -*-

def insertion_sort(A):
    """插入排序,作為桶排序的子排序"""
    n = len(A)
    if n <= 1:
        return A
    B = [] # 結(jié)果列表
    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(A)
    1  n ← length[A] // 桶數(shù)
    2  for i ← 1 to n
    3    do insert A[i] into list B[floor(nA[i])] // 將n個(gè)數(shù)分布到各個(gè)桶中
    4  for i ← 0 to n-1
    5    do sort list B[i] with insertion sort // 對(duì)各個(gè)桶中的數(shù)進(jìn)行排序
    6  concatenate the lists B[0],B[1],...,B[n-1] together in order // 依次串聯(lián)各桶中的元素

    桶排序假設(shè)輸入由一個(gè)隨機(jī)過(guò)程產(chǎn)生,該過(guò)程將元素均勻地分布在區(qū)間[0,1)上。
    """
    n = len(A)
    buckets = [[] for _ in xrange(n)] # n個(gè)空桶
    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))

相關(guān)文章

最新評(píng)論