基于array实现最大堆,当事先知道堆的最大容量时通常可以用array实现。如果最大容量无法确定,那么可以使用list替代。
import array as Array
class MaxHeap:
def __init__(self,maxSize):
self._elements = Array(maxSize)
self._count = 0
def __len__( self ):
return self._count
def capacity( self ):
return len( self._elements )
def add( self, value ):
assert self._count < len( self._elements ), ""
self._elements[self._count] = value
self._count += 1
self._siftUp( self._count - 1 )
#delete maximum from heap
def extract( self ):
assert self._count > 0,""
value = self._elements[0]
self._elements[0] = self._elements[self._count-1]
self._siftDown(0)
def _siftUp( self, ndx ):
if ndx > 0 :
parent = ndx // 2
if self._elements[ndx] > self._elements[parent]:
tmp = self._elements[parent]
self._elements[parent] = self._elements[ndx]
self._elements[ndx] = tmp
self._siftUp( parent )
def _siftDown( self, ndx ):
left = 2 * ndx + 1
right = 2* ndx + 2
largest = ndx
if left < count and self._elements[left] >= self._elements[largest]:
largest = left
if right < count and self._elements[right] >= self._elements[largest]:
largest = right
if largest != ndx:
swap( self._elements[ndx], self._elements[largest] )
_siftDown( largest )