python 最大堆

HeapAdjust 的作用是从父节点开始遍历出一条路径,逐渐找到最大值并找到最大值。时间复杂度为log(n),一共进行了n次操作所以总的时间复杂度为nlog(n)

for i in range(0,length//2+1)[::-1]: HeapAdjust(sorted_list,i,length)首先初始化最大堆,保证父节点比子节点的值要大。这里巧妙地用了HeapAdjust函数,因为最大堆是一个完全二叉树,我们只需要对长度一半+1的节点进行调整就能实现初始化的功能

def HeapSort(input_list):
    def HeapAdjust(input_list,parent,length):
        temp=input_list[parent]
        child=2*parent+1
        while child<length:
            if child+1 < length and input_list[child]<input_list[child+1]:
                child+=1
            if temp>input_list[child]:
                break
            input_list[parent]=input_list[child]
            parent=child
            child=2*child+1
        input_list[parent]=temp
    if input_list==[]: 
        return []
    sorted_list=input_list[:]
    length=len(sorted_list)
    for i in range(0,length//2+1)[::-1]:
        HeapAdjust(sorted_list,i,length)
    for j in range(1,length)[::-1]:
        temp=sorted_list[j]
        sorted_list[j]=sorted_list[0]
        sorted_list[0]=temp
        HeapAdjust(sorted_list,0,j)
        print('%dth' %(length-j))
        print(sorted_list)
    return sorted_list
if __name__=='__main__':
    input_list=[50,123,543,187,49,30,0,2,11,100]   
    print(input_list)
    sorted_list=HeapSort(input_list)
    print(sorted_list)
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值