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"; }
/** * Kruskal's algorithm to find a minimum-cost spanning tree * for the given edge-weighted, undirected graph. * Uses a partition and a priority queue. * * @param object IGraph $g An edge-weighted, undirected graph. * It is assumed that the edge weights are <code>Int</code>s * @return object IGraph An unweighted, undirected graph that represents * the minimum-cost spanning tree. */ public static function kruskalsAlgorithm(IGraph $g) { $n = $g->getNumberOfVertices(); $result = new GraphAsLists($n); for ($v = 0; $v < $n; ++$v) { $result->addVertex($v); } $queue = new BinaryHeap($g->getNumberOfEdges()); foreach ($g->getEdges() as $edge) { $weight = $edge->getWeight(); $queue->enqueue(new Association($weight, $edge)); } $partition = new PartitionAsForest($n); while (!$queue->isEmpty() && $partition->getCount() > 1) { $assoc = $queue->dequeueMin(); $edge = $assoc->getValue(); $n0 = $edge->getV0()->getNumber(); $n1 = $edge->getV1()->getNumber(); $s = $partition->findItem($n0); $t = $partition->findItem($n1); if ($s !== $t) { $partition->join($s, $t); $result->addEdge($n0, $n1); } } return $result; }