数据结构之堆排序(python实现)

'''
特性:
1.最大堆的堆顶是整个堆中的最大元素
2.最小堆的堆顶是整个堆中的最小元素
堆排序算法的步骤:
1.把无序数组构建成二叉堆。需要从小到大排序,则构建成最大堆;需要从大到小排序,则构建成最小堆。
2.循环删除堆顶元素,替换到二叉堆的末尾,调整堆产生新的堆顶。
'''
def downAdjust(string,parentIndex,length):
    #temp保存父节点值,用于最后的赋值
    temp=string[parentIndex]
    childIndex=parentIndex*2+1
    while childIndex<length:
        #如果有右孩子,且右孩子大于左孩子的值,则定位到右孩子
        if(childIndex+1<length and string[childIndex+1]>string[childIndex]):
            childIndex+=1
        #如果父节点大于任何一个孩子的值,则直接跳出
        if(temp>=string[childIndex]):
            break
        string[parentIndex]=string[childIndex]
        parentIndex=childIndex
        childIndex=parentIndex*2+1
    string[parentIndex]=temp

def headSort(string):
    #把无序数组构建成最大堆
    b=int((len(string) - 2) / 2)
    for i in range(b,-1,-1):
        downAdjust(string,i,len(string))
    print(string)
    #循环删除堆顶元素
    for j in range(len(string)-1,0,-1):
        temp=string[j]
        string[j]=string[0]
        string[0]=temp
        downAdjust(string,0,j)
string=[1,3,2,6,5,7,8,9,10]
headSort(string)
print(string)
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值