关闭

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

标签: 数据结构python
467人阅读 评论(0) 收藏 举报
分类:

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

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:6756次
    • 积分:330
    • 等级:
    • 排名:千里之外
    • 原创:13篇
    • 转载:5篇
    • 译文:14篇
    • 评论:3条