SPL data structure 2-heap, maximum heap, minimum heap

Time:2021-7-28

Heap is a common data structure. The bottom layer is a binary tree implemented by array. But there are no parent and child pointers. Sort according to heap properties. It is divided into minimum heap and maximum heap.

  • Minimum heap: the value of the parent node is smaller than that of each child node
  • Maximum heap: the value of the parent node is greater than that of each child node

It is generally used in the following scenarios:

  • Quick sort (max min)
  • Priority queue

Max / min heap

Splheap abstract class in SPL implements heap data structure. Splmaxheap and splminheap inherit from splheap and are used to realize maximum heap and minimum heap respectively. The following code takes the maximum heap as an example. The minimum heap is similar to the maximum heap

//Maximum heap
$maxheap = new SplMaxHeap();
//Insert node and rebuild heap
$maxheap->insert(12);
$maxheap->insert(3);
$maxheap->insert(222);
$maxheap->insert(2);
$maxheap->insert(312);
$maxheap->insert(3);
$maxheap->insert(13);
$maxheap->insert(32);
$maxheap->insert(3);
$maxheap->insert(1);


Echo "maximum push top level element:". $maxheap - > top(). PHP_ EOL;

//Extract extract top-level elements
//Take out the node and rebuild the heap 
echo "extract:" . $maxheap->extract() . PHP_EOL;
echo "extract:" . $maxheap->extract() . PHP_EOL;
echo "extract:" . $maxheap->extract() . PHP_EOL;

Echo "determine whether it is an empty heap:". PHP_ EOL;
var_dump($maxheap->isEmpty());
//When the heap length is 0, the heap is empty
Echo "current heap length:". $maxheap - > count(). PHP_ EOL;

Implement custom push sort

Many times, the simple number size comparison can not meet our requirements for heap data structure. For example, we need to implement heap sorting based on complex arrays. Splheap class provides the compare abstract method. As long as we implement our own compare method, we can sort the minimum heap and maximum heap of any data type

class MmaxHead extends SplHeap
{

    /**
     *Save the ranking information as student association information in the array
     * ['name'=>'Bob',score=>99.2]
     * 
     * @param mixed $value1
     * @param mixed $value2
     * 
     * @return int
     */
    protected function compare($value1, $value2)
    {
        if ($value1['score'] > $value2['score']) {
            return 1;
        } elseif ($value1['score'] < $value2['score']) {
            return -1;
        } else {
            return 0;
        }

    }
}

$myheap = new MmaxHead();
$myheap->insert(['name' => "bob1", "score" => 65]);
$myheap->insert(['name' => "bob2", "score" => 34.3]);
$myheap->insert(['name' => "bob3", "score" => 99.3]);
$myheap->insert(['name' => "bob4", "score" => 23.4]);
$myheap->insert(['name' => "bob5", "score" => 55]);
$myheap->insert(['name' => "bob6", "score" => 66]);


Echo "the highest score is". PHP_ EOL;
var_dump($myheap->top());

Echo "rank in order:". PHP_ EOL;
while (!$myheap->isEmpty()) {
    var_dump($myheap->extract());
}

Priority queue

The priority queue splpriorityqueue has been provided for us in SPL. Splpriorityqueue is implemented based on the maximum heap, that is, the higher the priority, the first out of the queue. You can rewrite compare to small priority first out queue (minimum heap), and you can also implement your own business logic by integrating rewrite compare

$objPQ = new SplPriorityQueue();

$objPQ->insert('A',3);
$objPQ->insert('B',6);
$objPQ->insert('C',1);
$objPQ->insert('D',2);

Echo "priority queue length:". $objpq - > count(). PHP_ EOL;


/**
 *Set element out of queue mode
 * SplPriorityQueue::EXTR_ Data extracts only values
 * SplPriorityQueue::EXTR_ Priority extracts priority only
 * SplPriorityQueue::EXTR_ Both extraction array contains values and priorities
 */
//Acquiescence
$objPQ->setExtractFlags(SplPriorityQueue::EXTR_DATA);
Echo "top extract value:" $objpq - > top(). PHP_ EOL;

$objPQ->setExtractFlags(SplPriorityQueue::EXTR_PRIORITY);
Echo "top extraction priority:". $objpq - > top(). PHP_ EOL;

$objPQ->setExtractFlags(SplPriorityQueue::EXTR_BOTH);
Echo "top returns an array including values and priorities:". PHP_ EOL;
var_dump($objPQ->top());

//Traversal:
$objPQ->setExtractFlags(SplPriorityQueue::EXTR_DATA);
while($objPQ->valid()){
    print_r($objPQ->current());
    $objPQ->next();
}

Previous:Bidirectional linked list, stack, queue
Next:SPL data structure 3-splfixedarray

Recommended Today

Implementation example of go operation etcd

etcdIt is an open-source, distributed key value pair data storage system, which provides shared configuration, service registration and discovery. This paper mainly introduces the installation and use of etcd. Etcdetcd introduction etcdIt is an open source and highly available distributed key value storage system developed with go language, which can be used to configure sharing […]