class Heap:
def __init__(self):
self.data=[]
@staticmethod
def _parent(idx):
return (idx-1)//2
@staticmethod
def _left(idx):
return idx*2+1
@staticmethod
def _right(idx):
return idx*2+2
def max(self):
return self.data[0]
def add(self,x):
self.data.append(x)
i=len(self.data)-1
while i>0:
p=Heap._parent(i)
if self.data[i]>self.data[p]:
self.data[i],self.data[p]=self.data[p],self.data[i]
i=p
else:
break
def pop_max(self):
m=self.data[0]
self.data[0]=self.data[-1]
del self.data[-1]
i=0
while i<len(self.data):
l=Heap._right(i)
r=Heap._left(i)
mi=i
if l<len(self.data) and self.data[l]>self.data[i]:
mi=l
if r<len(self.data) and self.data[r]>self.data[mi]:
mi=r
if mi!=i:
self.data[i],self.data[mi]=self.data[mi],self.data[i]
i=mi
else:
break
return m
def __repr__(self):
return repr(self.data)
def __bool__(self):
return len(self.data)>0
判断是否为最大堆
def judgeIsMaxHeap(heapList):
heapLenght=len(heapList)
if heapList[0]>heapList[-1]:
for i in range((heapLenght//2)):
if (2*i+2)>=heapLenght:
if heapList[i]>=heapList[2*i+1]:
print(i)
continue
else:
return False
elif heapList[i]>=heapList[2*i+1] and heapList[i]>=heapList[2*i+2]:
continue
else:
return False
return True
heapList=[9, 8, 5, 6, 7, 3, 0, 1, 2, 4]
print(judgeIsMaxHeap(heapList))
|