Behold the Priority Queue / Minheap... In PHP! :D Stay tuned for the Ruby edition!

I couldn't find any decent implementations of the bottom-up heap so I wrote one myself! I'm currently working on finding the quickest route between bus stops using Dijkstra's Algorithm which requires a priority queue with decrease key. Hope this snippet saves someone some time :P

The MIT License

Copyright (c) 2010 Richard Ramsden

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

<?php class PriorityQueue { /** * Min Heap * * [2*n + 1] - first child of [n] * [2*n + 2] - second child of [n] */ private $heap; public function push($element) { $count = count($this->heap); $this->heap[$count] = $element; $this->bubbleUp($count); } public function IsEmpty() { return (count($this->heap) == 0) ? true : false; } public function decreaseKey($i) { $this->heap[$i] = 9999; $this->bubbleDown($i); } private function bubbleUp($i) { $parent = floor(($i-1)/2); if($this->less($this->heap[$i], $this->heap[$parent]) and ($parent >= 0)) { $this->swap($i, $parent); $this->bubbleUp($parent); } } private function bubbleDown($i) { $left = 2*$i+1; $right = 2*$i+2; // check left subtree if($this->heap[$i] > $this->heap[$left] and $left < count($this->heap)) { $this->swap($i, $left); $this->bubbleDown($left); } // check right subtree if($this->heap[$i] > $this->heap[$right] and $right < count($this->heap)) { $this->swap($i, $right); $this->bubbleDown($right); } } private function swap($x, $y) { $tmp = $this->heap[$x]; $this->heap[$x] = $this->heap[$y]; $this->heap[$y] = $tmp; } public function top() { if (count($this->heap) == 0) return null; return $this->heap[0]; } public function pop() { $tmp = $this->heap[0]; $this->swap(0, count($this->heap)-1); unset($this->heap[count($this->heap)-1]); $this->bubbleDown(0); return $tmp; } public function clear() { $this->heap = array(); } private function less($ele1, $ele2) { return ($ele1 < $ele2) ? true : false; } } ?>