【演算法】DAY5_演算法

來源:互聯網
上載者:User
# 快速排序from random_int_list import random_int_list# 產生隨機數組A = random_int_list(1,50,50)length = len(A)# 利用主元將數組分成大小兩部分def partition(A, p ,r):    # 保證演算法隨機性    random = random_int_list(p, r)[0]    A[random], A[r] = A[r], A[random]    key = A[r]    m = p - 1    for n in range(p, r):        if A[n] < A[r]:            m += 1            A[m], A[n] = A[n], A[m]    A[m+1], A[r] = A[r], A[m+1]    return m+1# 快速排序主程式def quickSort(A, p, r):    if p < r:        q = partition(A, p ,r)        quickSort(A, p, q-1)        quickSort(A, q+1, r)def quickSortEnter(A):    quickSort(A, 0, length-1)# testprint(A)quickSortEnter(A)print(A)# 計數排序from random_int_list import random_int_list# 產生隨機數組numberRange = 50amount = 50A = random_int_list(1, numberRange, amount)# 主程式def countingSort(A):    B = []  # 排序完成的數組    C = []  # 數字數量數組    for n in range(numberRange+1):        C.append(0)    for n in range(amount):        B.append(0)    # 計算每個數字出現的次數,並累加形成排序後每個數字第一次出現時應在的位置    for n in range(amount):        C[A[n]] += 1    for n in range(1, numberRange+1):        C[n] += C[n-1]    # 根據每個數字第一次出現時應在的位置,進行排序    for n in range(amount-1, -1, -1):        B[C[A[n]]-1] = A[n]        C[A[n]] -= 1    return B# testprint(A)B = countingSort(A)print(B)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.