用數組實現-堆-算法

堆有大頂堆,小頂堆;大頂堆保證堆頂元素爲堆中最大值,小頂堆相反。(大頂)堆的特性是父節點的值大於子節點的值。

對於堆來說:

Index_{parent}=(Index_{child}-1)/2

Index_{Leftchild}=2*Index_{parent}+1

Index_{Rightchild}=2*Index_{parent}+2

class Heap

{

array []

  • top()
  • push()
  • dropTop()

}

top:

 return array[0]

push:

while(index>0)
{
int parentIndex=(index-1)/2;
if(array[index]>array[parentIndex])
    exchage(array[index],array[parentIndex]);

else

    break;

index=parentIndex;
}

dropTop:

exchage(array[0],array[size-1]);
array.pop_back();
while(2*index+1<size)
{
int child_index=2*index+1;
if(child_index<size)
child_index=array[child_index]>heap[child_index+1]?child_index:child_index+1;
if(array[child_index]>array[index])
exchage(array[child_index],array[index]);
else
break;
index=child_index;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章