Python实现堆排序

1.调整成为大根堆

#调整成为大根堆
def Max_Heapify(heap,i,length):
   '''
   :param heap: 数组名
   :param i: 父节点下标
   :param length: 数组中元素个数
   '''
   lchild=2*i+1
   rchild=2*i+2
   max=i
#递归出口
   if i>=length:
       return False
   if lchild<length and heap[max]<heap[lchild]:
       max=lchild
   if rchild < length and heap[max] < heap[rchild]:
           max = rchild
#此时已经得到了最大元素的下标,接下来进行交换操作
   if max!=i:
    heap[max],heap[i]=heap[i],heap[max]
#继续递归
    Max_Heapify(heap,max,length)

2.建立一个堆(从最后一个非叶节点开始)

#建立一个堆(从最后一个非叶节点开始)
def Build_Heapy(heap):
        for i in range((len(heap)-1)//2,-1,-1):
            Max_Heapify(heap,i,len(heap))

3.进行堆排序

#进行堆排序
def Sort_Heapy(heap):
        #首先是建堆
        Build_Heapy(heap)
        # 不断的将根结点与最后一个结点交换
        for i in range (len(heap)-1,-1,-1):
            heap[0],heap[i]=heap[i],heap[0]
        #然后重新调整为大根堆
            Max_Heapify(heap,0,i)

完整代码如下:

#调整成为成大根堆
def Max_Heapify(heap,i,length):
   '''
   :param heap: 数组名
   :param i: 父节点下标
   :param length: 数组中元素个数
   '''
   lchild=2*i+1
   rchild=2*i+2
   max=i
#递归出口
   if i>=length:
       return False
   if lchild<length and heap[max]<heap[lchild]:
       max=lchild
   if rchild < length and heap[max] < heap[rchild]:
           max = rchild
#此时已经得到了最大元素的下标,接下来进行交换操作
   if max!=i:
    heap[max],heap[i]=heap[i],heap[max]
#继续递归
    Max_Heapify(heap,max,length)


#建立一个堆(从最后一个非叶节点开始)
def Build_Heapy(heap):
        for i in range((len(heap)-1)//2,-1,-1):
            Max_Heapify(heap,i,len(heap))


#进行堆排序
def Sort_Heapy(heap):
        #首先是建堆
        Build_Heapy(heap)
        # 不断的将根结点与最后一个结点交换
        for i in range (len(heap)-1,-1,-1):
            heap[0],heap[i]=heap[i],heap[0]
        #然后重新调整为大根堆
            Max_Heapify(heap,0,i)

if __name__ == '__main__':
    heap=[8,2,9,1,0,6]
    Sort_Heapy(heap)
    print(heap)

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值