堆(Heap)AS3版

當應用優先級隊列或者進行堆排序時,一般利用堆來實現。堆是一個完全二叉樹,並滿足如下條件:
1、根結點若有子樹,則子樹一定也是堆。
2、根結點一定大於(或小於)子結點。
因爲要求堆必須是完全二叉樹,所以使用數組實現堆要比結點實現更有效率。
利用數組實現,則對於長爲N的堆中的元素從0到N-1排列,有:
1、i 的父結點:Parent(i)=(i+1)/2-1
2、i 的左葉子:Left(i)=(i+1)*2-1
3、i 的右葉子:Right(i)=(i+1)*2
堆的插入和刪除很有意思。在堆的數據結構中,堆中的最大值總是位於根節點。堆中定義了以下幾種操作,在堆中進行了上述操作後,堆的特殊屬性可能發生變化。例如,當在堆尾插入一個數據,它可能大於它的父節點,因而需要進行一系列的置換操作,調整它的位置,從而保持堆的特有屬性。和此相關的操作包括:
篩選上移(sift_up):給定某個數據後,將其上移到相應的位置,從而保證其值不大於父節點。
篩選下移(sift_down):給定某個數據後,將其下移到相應的位置,從而保證其值不大於父節點。
堆主要應用在排序算法中。


package kono.utils
{
//堆,基於數組, Heap, built on a array
public class Heap
{
private var _heap:Array;
private var _top:uint;
private var capacity:uint;
private var compare:Function;

public function Heap(size:uint, compareTo:Function = null)
{
_heap = new Array(capacity = size);
_top = 0;
if(compareTo == null)
{
compare = function (a:Number, b:Number):int
{
return int(a-b);
}
}
else
{
compare = compareTo;
}
}

//得到堆的大小, get the heap????s capacity
public function get size():uint
{
return capacity;
}

//堆首, the first data in the heap
public function peek():*
{
return _heap[0];
}

//添加新數據到堆(sift_up), add a new data to heap
public function push(data:*):void
{
_heap[_top] = data;
var parents:uint = (_top - 1) >> 1;
while(_top > 0 && parents >= 0)
{
if(compare(_heap[_top], _heap[parents]) > 0)
{
var temp:* = _heap[parents];
_heap[parents] = _heap[_top];
_heap[_top] = temp;
if(parents > 0)
parents = (parents - 1) >> 1;
}
else
break;
}
_top ++;
}

//刪除堆首元素(sift_down), remove the first data in the heap
public function pop():void
{
if(_top > 0)
{
_heap[0] = _heap[_top -1];
var cursor:uint = 0;
var childs:uint = (_top << 1) + 1;
childs = _heap[childs] > _heap[childs + 1] ? childs : childs + 1;
while(childs < _top)
{
if(compare(_heap[cursor], _heap[childs]) < 0)
{
var temp:* = _heap[cursor];
_heap[cursor] = _heap[childs];
_heap[childs] = temp;
cursor = childs;
}
else
break;
}
_top--;
}
delete _heap[_top];
}

//打印堆結構, print the frame of the heap
public function print():void
{
var space:String = " ";
for(var i:uint = 0; i < _heap.length; i++)
{
space += " ";
trace(space + _heap[i]);
}
}

//清空堆, remove all the data of the heap
public function clear():void
{
_heap = new Array(capacity);
_top = 0;
}

//判斷給定數據是否包含在堆中, check if the given target exit in the heap
public function contains(target:*):Boolean
{
for(var i:uint = 0; i < _heap.length; i++)
{
if(_heap[i] == target)
{
return true;
}
}
return false;
}

//轉換堆到數組, convert the heap to a array
public function toArray():Array
{
return _heap;
}

//返回堆的信息, return a string respreaenting the current heap
public function toString():String
{
return "[Heap, size=" + capacity + "]";
}
}
}

本文轉自
http://www.moorwind.com/read.php?42
發佈了108 篇原創文章 · 獲贊 24 · 訪問量 100萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章