手记

[硕.Love Python] HeapSort(堆排序)

def adjust(a, root, n):
    k = a[root-1]
    c = root * 2

    while c <= n:
        if c + 1 <= n and a[c] > a[c-1]:
            c += 1

        if a[c-1] <= k:
            break

        a[c/2-1] = a[c-1]
        c *= 2

    a[c/2-1] = k

def heapSort(a):
    n = len(a)

    for i in xrange(n / 2, 0, -1):
        adjust(a, i, n)

    for i in xrange(n - 1, 0, -1):
        a[0], a[i] = a[i], a[0]
        adjust(a, 1, i)

if __name__ == '__main__':
    from random import shuffle

    data = range(100)
    shuffle(data)

    print data
    heapSort(data)
    print data
0人推荐
随时随地看视频
慕课网APP