Using SplHeap, SplMaxHeap, and SplMinHeap

If we do not want to implement our own Heap implementations, we can use the built-in heap classes from the Standard PHP Library - SPL. SPL has three different implementations for the heap. One for generic Heap, which is SplHeap, for MaxHeap we have SplMaxHeap, and for MinHeap we have SplMinHeap. It is important to know that SPL classes are not considered as very performant while running on PHP 7. So we are not going to explore in details about them here. We will just focus on a sample example here so that if we are using any other version than PHP 7, we can use those built-in classes. Let us try an example using SplMaxHeap:

$numbers = [37, 44, 34, 65, 26, 86, 143, 129, 9]; 

$heap = new SplMaxHeap;

foreach ($numbers as $number) {
$heap->insert($number);
}

while (!$heap->isEmpty()) {
echo $heap->extract() . " ";
}

Since we have used max-heap, we are expecting the output to be in descending order. Here is the output from the command line:

143     129     86      65      44      37      34      26      9

If we want to sort it the other way around, we can use SplMinHeap for that.

..................Content has been hidden....................

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