Home > Article > Backend Development > Simple usage example of data structure heap (SplHeap) of PHP SPL standard library_PHP tutorial
This article mainly introduces a simple usage example of the data structure heap (SplHeap) of the PHP SPL standard library. This article also explains the relevant knowledge of the maximum heap (SplMaxHeap) and the minimum heap (SplMinHeap). Friends in need can refer to it
Heap is a data structure designed to implement priority queues. It is implemented 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:
?
10 11
12
13
14
15
16
17
18
19
20
|
class MySimpleHeap extends SplHeap { //The compare() method is used to compare the size of two elements and determine their positions in the heap 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; } |