python演算法學習之計數排序執行個體_python

來源:互聯網
上載者:User

python演算法學習之計數排序執行個體

複製代碼 代碼如下:

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

def _counting_sort(A, B, k):
    """計數排序,偽碼如下:
    COUNTING-SORT(A, B, k)
    1  for i ← 0 to k // 初始化儲存區的值
    2    do C[i] ← 0
    3  for j ← 1 to length[A] // 為各值計數
    4    do C[A[j]] ← C[A[j]] + 1
    5  ▷ C[i]包含等於i的元素個數
    6  for i ← 1 to k // 求計數和,確定<=各值的元素數
    7    do C[i] ← C[i] + C[i-1]
    8  ▷ C[i]包含小於或等於i的元素個數
    9  for j ← length[A] downto 1
    10   do B[C[A[j]]] ← A[j] // 將A[j]值放到對應位置
    11      C[A[j]] ← C[A[j]] - 1 // 避免元素相同時覆蓋同一位置

    T(n) = θ(n)

    Args:
        A (Sequence): 原數組
        B (Sequence): 結果數組
        k (int): 值上限,假定了所有元素介於[0,k]
    """
    len_c = k + 1
    C = [0] * len_c
    for a in A:
        C[a] = C[a] + 1
    for i in range(1, len_c):
        C[i] = C[i] + C[i-1]
    for a in A[::-1]:
        B[C[a]-1] = a
        C[a] = C[a] - 1

def counting_sort(A):
    """假定A數組所有元素都介於[0,len(A)-1]"""
    B = [0] * len(A)
    _counting_sort(A, B, len(A) - 1)
    return B

if __name__ == '__main__':
    import random, timeit

    items = range(10000)
    random.shuffle(items)

    def test_sorted():
        print(items)
        sorted_items = sorted(items)
        print(sorted_items)

    def test_counting_sort():
        print(items)
        sorted_items = counting_sort(items)
        print(sorted_items)

    test_methods = [test_sorted, test_counting_sort]
    for test in test_methods:
        name = test.__name__ # test.func_name
        t = timeit.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.