Home > Article > Backend Development > Simple usage example of data structure heap (SplHeap) of PHP SPL standard library, splsplheap_PHP tutorial
Heap is a data structure designed to implement priority queues. It is This is achieved by constructing a binary heap (a type of binary tree). The heap with the largest root node is called the maximum heap or large root heap, and the heap with the smallest root node is called the minimum heap or small root heap. Binary heaps are also commonly used for sorting (heap sort).
As follows: Minimum heap (the priority of any node is not less than its child node)
Look at the implementation of PHP SplHeap:
Obviously it is an abstract class, and the maximum heap (SplMaxHeap) and the minimum heap (SplMinHeap) are implemented by inheriting it. There are no additional methods for max-heap and min-heap
The simple use of SplHeap is as follows:
class MySimpleHeap extends SplHeap { //compare()方法用来比较两个元素的大小,绝对他们在堆中的位置 public function compare( $value1, $value2 ) { return ( $value1 - $value2 ); } } $obj = new MySimpleHeap(); $obj->insert( 4 ); $obj->insert( 8 ); $obj->insert( 1 ); $obj->insert( 0 ); echo $obj->top(); //8 echo $obj->count(); //4 foreach( $obj as $number ) { echo $number; }