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)
    

猜你喜欢

转载自blog.csdn.net/Neekity/article/details/87937885