python演算法學習之桶排序演算法執行個體(分塊排序)

來源:互聯網
上載者:User
複製代碼 代碼如下:


# -*- 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] // 桶數
2 for i ← 1 to n
3 do insert A[i] into list B[floor(nA[i])] // 將n個數分布到各個桶中
4 for i ← 0 to n-1
5 do sort list B[i] with insertion sort // 對各個桶中的數進行排序
6 concatenate the lists B[0],B[1],...,B[n-1] together in order // 依次串聯各桶中的元素

桶排序假設輸入由一個隨機過程產生,該過程將元素均勻地分布在區間[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))

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    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.