算法-Python2.7实现用数组看作堆来实现最优先队列(最大堆)

废话不多说,直接上代码

# coding=UTF-8
import numpy as np

def sift_down(parent):               #向下调整
    i = parent
    j = 2*i+1
    tmp = npyArray[parent]
    while(j < len(npyArray)):
        if((j < len(npyArray)-1) and npyArray[j] < npyArray[j+1]):
            j += 1
        if(tmp < npyArray[j]):
            npyArray[i] = npyArray[j]
            i = j
            j = 2*i + 1
        else: break
    npyArray[i] = tmp
npyArray = [16,14,8,10,9,7,3,2,4,1 ]
i = int( len(npyArray) / 2 - 1)
while(i >= 0):
    sift_down(i)
    i -= 1
print "The array representation of the heap is", npyArray

 

输出结果:The array representation of the heap is [16 14 10  8  7  9  3  2  4  1] 

 

如果对你有帮助的话,给我点个赞,让我分享一些技术的时候更有动力。

另外我建了一个公众号,会不时分享前端的一些技术,或者遇到的难题和解决办法,欢迎大家关注。

搜索:钱端工程师       或        Money-end-engineer      或       扫描下方图片

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值