# Python数据结构----最大堆

682人阅读 评论(0)

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 )

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 )
0
0

个人资料
• 访问：9632次
• 积分：359
• 等级：
• 排名：千里之外
• 原创：13篇
• 转载：5篇
• 译文：14篇
• 评论：3条
阅读排行