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

来源:互联网 发布:seo全网优化指南 pdf 编辑:程序博客网 时间:2024/05/30 23:42
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


刘硕老师Python精品课程:

Python高级编程技巧实战》:

http://coding.imooc.com/class/62.html

 

Python算法实战视频课程》:

http://edu.csdn.net/combo/detail/174

 

Python科学计算—NumPy实战课程》:

http://edu.51cto.com/course/course_id-5046.html

 

熊猫TV直播间:

http://www.panda.tv/671023



0 0
原创粉丝点击