算法导论(Python版本)(第8章)

1. 桶排序

def INSERTION_SORT(A):
    for j in range(1, len(A)):
        key = A[j]
        i = j - 1
        while i >= 0 and A[i] > key:
            A[i+1] = A[i]
            i -= 1
        A[i+1] = key
    return A

def BUCKET_SORT(A):
    n = len(A)
    B = [[] for i in range(n)]
    for i in range(n):
        B[int(A[i]*n)].append(A[i])
    for j in range(n):
        B[j] = INSERTION_SORT(B[j])
    del A[:]
    for k in range(n):
        A.extend(B[k])
    return A

A = [0.78,0.17,0.39,0.26,0.72,0.94,0.21,0.12,0.23,0.68]
print(BUCKET_SORT(A))

 

你可能感兴趣的:(算法导论(Python版本)(第8章))