コード例 #1
0
    public function insert($item)
    {
        // insert new items at the bottom of the heap
        $this->heap[] = $item;
        // trickle up to the correct location
        $place = $this->count();
        $parent = floor($place / 2);
        // while not at root and greater than parent
        while ($place > 0 && $this->compare($this->heap[$place], $this->heap[$parent]) >= 0) {
            // swap places
            list($this->heap[$place], $this->heap[$parent]) = array($this->heap[$parent], $this->heap[$place]);
            $place = $parent;
            $parent = floor($place / 2);
        }
    }
}
$heap = new BinaryHeap();
$heap->insert(19);
$heap->insert(36);
$heap->insert(54);
$heap->insert(100);
$heap->insert(17);
$heap->insert(3);
$heap->insert(25);
$heap->insert(1);
$heap->insert(67);
$heap->insert(2);
$heap->insert(7);
while (!$heap->isEmpty()) {
    echo $heap->extract() . "\n";
}