Home  >  Article  >  Backend Development  >  Simple usage example of data structure heap (SplHeap) of PHP SPL standard library, splsplheap_PHP tutorial

Simple usage example of data structure heap (SplHeap) of PHP SPL standard library, splsplheap_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 09:54:01943browse

A simple usage example of the data structure heap (SplHeap) of the PHP SPL standard library. splsplheap

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;
}

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/998575.htmlTechArticlePHP SPL standard library data structure heap (SplHeap) simple usage example, splsplheap heap (Heap) is to achieve priority A data structure designed for queues. It is constructed by constructing a binary heap (binary tree...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn