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

1. 快速排序

import random

def PARTION(A, p, r):
    x = A[r]
    i = p - 1
    for j in range(p, r):
        if A[j] <= x:
            i += 1
            A[i], A[j] = A[j], A[i]
    A[i+1], A[r] = A[r], A[i+1]
    return i+1


def QUICK_SORT(A, p, r):
    if p < r:
        q = RANDOMIZED_PARTION(A, p, r)
        QUICK_SORT(A, p, q-1)
        QUICK_SORT(A, q+1, r)
    return A

def RANDOMIZED_PARTION(A, p, r):
    i = random.randint(p, r)
    A[i], A[r] = A[r], A[i]
    return PARTION(A, p, r)


a = [324, 99, 3, 392, 543, 573]
print(QUICK_SORT(a, 0, 5))

 

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