废话不多说,直接上代码
# 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 或 扫描下方图片