Implement a priority queue using SplPriorityQueue

PHP already has a built-in support for implementing a priority queue using SPL. We can use the SplPriorityQueue class to implement our priority queues. Here is the sample previous example using a linked list, but this time we are choosing SPL:

class MyPQ extends SplPriorityQueue { 

public function compare($priority1, $priority2) {
return $priority1 <=> $priority2;
}

}

$agents = new MyPQ();

$agents->insert("Fred", 1);
$agents->insert("John", 2);
$agents->insert("Keith", 3);
$agents->insert("Adiyan", 4);
$agents->insert("Mikhael", 2);

//mode of extraction
$agents->setExtractFlags(MyPQ::EXTR_BOTH);

//Go to TOP
$agents->top();

while ($agents->valid()) {
$current = $agents->current();
echo $current['data'] . " ";
$agents->next();
}

This will produce the same result as the linked list example. The added advantage of extending to our own MyPQ class is that we can define whether we want to sort it in ascending or descending order. Here, we are choosing a descending order, sorting using a PHP combined comparison operator, or the spaceship operator.

Most of the time, priority queues are implemented using heap. When we move on to the heap chapter, we will also implement a priority queue using heap.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset