python实现计数排序 --算法导论

def COUNTING_SORT(A, B, k):
    C = list(range(k))
    for i in range(0, k):
        C[i] = 0
    for j in range(0, len(A)):
        C[A[j] - 1] += 1
    for i in range(1, k):
        C[i] = C[i] + C[i - 1]
    for j in range(len(A),0,-1):
        B[C[A[j - 1] - 1] - 1] = A[j - 1]
        C[A[j - 1] - 1] -= 1
    print(A)
    print(B)
    return A
A = [1, 3, 5, 7, 2, 4, 6, 8]#输入排序前的数组
B = list(range(len(A)))
k = max(A)
COUNTING_SORT(A, B, k)

你可能感兴趣的:(算法导论,算法,python,排序算法,算法导论)