国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

python算法學習之桶排序算法實例(分塊排序)

2020-02-23 05:00:57
字體:
來源:轉載
供稿:網(wǎng)友

代碼如下:
# -*- coding: utf-8 -*-

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

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

發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 大荔县| 靖宇县| 黑山县| 安龙县| 台安县| 城固县| 丹巴县| 新乐市| 饶河县| 闵行区| 通许县| 大丰市| 邻水| 六安市| 新密市| 南安市| 额尔古纳市| 深泽县| 得荣县| 公安县| 曲阳县| 竹溪县| 潼南县| 乳源| 赣榆县| 邻水| 陆丰市| 会昌县| 新密市| 诸暨市| 沙洋县| 霍州市| 张掖市| 怀远县| 泰州市| 肥城市| 伽师县| 贵德县| 萨迦县| 九龙县| 许昌市|