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

本文提供了一个使用Python实现的堆排序算法实例。通过调整元素位置确保父节点总是大于或等于其子节点,从而形成最大堆。之后通过不断交换堆顶元素与最后一个元素并重新调整堆,最终实现数组的有序排列。
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.youkuaiyun.com/combo/detail/174

 

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

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

 

熊猫TV直播间:

http://www.panda.tv/671023



评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值