Home Backend Development PHP Tutorial PHP data structure: The secret of heap data structure, realizing efficient sorting and priority queue

PHP data structure: The secret of heap data structure, realizing efficient sorting and priority queue

Jun 01, 2024 pm 03:54 PM
heap php data structure

The heap data structure in PHP is a tree structure that satisfies the complete binary tree and heap properties (the parent node value is greater/less than the child node value), and is implemented using an array. The heap supports two operations: sorting (extracting the largest element from small to large) and priority queue (extracting the largest element according to priority). The properties of the heap are maintained through the heapifyUp and heapifyDown methods respectively.

PHP data structure: The secret of heap data structure, realizing efficient sorting and priority queue

Heap data structure in PHP: Revealing the secrets of sorting and priority queues

The heap is a tree-like data structure , it satisfies the following two properties:

  • Complete binary tree properties: Each node in the tree has two child nodes, or has no child nodes, forming a tree Complete binary tree.
  • Heap properties: The value of each parent node is greater than (or equal to) the value of its two child nodes (maximum heap) or less than (or equal to) its two children The value of the node (min-heap).

PHP Implementation

In PHP, we use arrays to implement the heap. The following is a maximum heap PHP implementation:

class MaxHeap {
    private $heap = array();
    private $size = 0;

    public function insert($value) {
        $this->heap[$this->size++] = $value;
        $this->heapifyUp($this->size - 1);
    }

    private function heapifyUp($index) {
        if ($index === 0) {
            return;
        }
        $parentIndex = intval(($index - 1) / 2);
        if ($this->heap[$index] > $this->heap[$parentIndex]) {
            $temp = $this->heap[$index];
            $this->heap[$index] = $this->heap[$parentIndex];
            $this->heap[$parentIndex] = $temp;
            $this->heapifyUp($parentIndex);
        }
    }

    public function extractMax() {
        if ($this->size === 0) {
            return null;
        }
        $max = $this->heap[0];
        $this->heap[0] = $this->heap[$this->size - 1];
        $this->size--;
        $this->heapifyDown(0);
        return $max;
    }

    private function heapifyDown($index) {
        $largestIndex = $index;
        $leftIndex = 2 * $index + 1;
        $rightIndex = 2 * $index + 2;
        if ($leftIndex < $this->size && $this->heap[$leftIndex] > $this->heap[$largestIndex]) {
            $largestIndex = $leftIndex;
        }
        if ($rightIndex < $this->size && $this->heap[$rightIndex] > $this->heap[$largestIndex]) {
            $largestIndex = $rightIndex;
        }
        if ($largestIndex !== $index) {
            $temp = $this->heap[$index];
            $this->heap[$index] = $this->heap[$largestIndex];
            $this->heap[$largestIndex] = $temp;
            $this->heapifyDown($largestIndex);
        }
    }
}
Copy after login

Practical case

Sort:

$heap = new MaxHeap();
$heap->insert(10);
$heap->insert(5);
$heap->insert(15);
$heap->insert(8);
$heap->insert(12);

while ($heap->size > 0) {
    echo $heap->extractMax() . " ";
}
Copy after login

Output: 15 12 10 8 5

Priority queue:

$heap = new MaxHeap();
$heap->insert(5);
$heap->insert(2);
$heap->insert(3);
$heap->insert(1);

while ($heap->size > 0) {
    $element = $heap->extractMax();
    echo "服务于元素 " . $element . "\n";
}
Copy after login

Output:
Serving element 5
Serving element 3
Serving element 2
Serve element 1

The above is the detailed content of PHP data structure: The secret of heap data structure, realizing efficient sorting and priority queue. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What is the difference between heap and stack What is the difference between heap and stack Nov 22, 2022 pm 04:12 PM

Differences: 1. The heap space is generally allocated and released by the programmer; while the stack space is automatically allocated and released by the operating system. 2. The heap is stored in the second-level cache, and the life cycle is determined by the garbage collection algorithm of the virtual machine; while the stack uses the first-level cache, which is usually in the storage space when it is called, and is released immediately after the call is completed. 3. The data structures are different. Heap can be regarded as a tree, while stack is a first-in, last-out data structure.

Deque in Python: Implementing efficient queues and stacks Deque in Python: Implementing efficient queues and stacks Apr 12, 2023 pm 09:46 PM

deque in Python is a low-level, highly optimized deque useful for implementing elegant and efficient Pythonic queues and stacks, which are the most common list-based data types in computing. In this article, Mr. Yun Duo will learn the following together with you: Start using deque to effectively pop up and append elements. Access any element in deque. Use deque to build an efficient queue. Start using deque to append elements to the right end of a Python list and pop up elements. The operations are generally very Efficient. If time complexity is expressed in Big O, then we can say that they are O(1). And when Python needs to reallocate memory to increase the underlying list to accept new elements, these

The difference between heap and stack The difference between heap and stack Jul 18, 2023 am 10:17 AM

The difference between heap and stack: 1. The memory allocation method is different. The heap is manually allocated and released by the programmer, while the stack is automatically allocated and released by the operating system. 2. The size is different. The size of the stack is fixed, while the stack is automatically allocated and released by the operating system. The size of is growing dynamically; 3. Data access methods are different. In the heap, data access is achieved through pointers, while in the stack, data access is achieved through variable names; 4. Data life cycle , In the heap, the life cycle of data can be very long, while in the stack, the life cycle of variables is determined by the scope in which they are located.

What are the differences between java heap and stack What are the differences between java heap and stack Dec 25, 2023 pm 05:29 PM

The difference between Java heap and stack: 1. Memory allocation and management; 2. Storage content; 3. Thread execution and life cycle; 4. Performance impact. Detailed introduction: 1. Memory allocation and management. The Java heap is a dynamically allocated memory area, mainly used to store object instances. In Java, objects are allocated through heap memory. When an object is created, the Java virtual machine Allocate corresponding memory space on the system, and automatically perform garbage collection and memory management. The size of the heap can be dynamically adjusted at runtime, configured through JVM parameters, etc.

Heap and priority queue in C++ Heap and priority queue in C++ Aug 22, 2023 pm 04:16 PM

Heap and priority queue are commonly used data structures in C++, and they both have important application value. This article will introduce and analyze the heap and priority queue respectively to help readers better understand and use them. 1. Heap is a special tree data structure that can be used to implement priority queues. In the heap, each node satisfies the following properties: its value is not less than (or not greater than) the value of its parent node. Its left and right subtrees are also a heap. We call a heap that is no smaller than its parent node a "min-heap" and a heap that is no larger than its parent node a "max-heap"

PHP data structure: The secret of heap data structure, realizing efficient sorting and priority queue PHP data structure: The secret of heap data structure, realizing efficient sorting and priority queue Jun 01, 2024 pm 03:54 PM

The heap data structure in PHP is a tree structure that satisfies the complete binary tree and heap properties (the parent node value is greater/less than the child node value), and is implemented using an array. The heap supports two operations: sorting (extracting the largest element from small to large) and priority queue (extracting the largest element according to priority). The properties of the heap are maintained through the heapifyUp and heapifyDown methods respectively.

What are the usage scenarios of heap and priority queue in Python? What are the usage scenarios of heap and priority queue in Python? Oct 28, 2023 am 08:56 AM

What are the usage scenarios of heap and priority queue in Python? The heap is a special binary tree structure that is often used to efficiently maintain a dynamic collection. The heapq module in Python provides a heap implementation and can easily perform heap operations. A priority queue is also a special data structure. Unlike an ordinary queue, each element of it has a priority associated with it. The highest priority element is taken out first. The heapq module in Python can also implement the priority queue function. Below we introduce some

PHP SPL data structures: the ultimate weapon for data management PHP SPL data structures: the ultimate weapon for data management Feb 20, 2024 am 11:30 AM

Introduction to PHPSPL Data Structure Library The PHP Standard Library (SPL) contains a rich set of built-in data types called data structures. These structures provide efficient and flexible management of complex data collections. Using SPL data structures can bring the following benefits to your application: Performance Optimization: SPL data structures are specifically designed to provide optimal performance in a variety of situations. Improved maintainability: These structures simplify the handling of complex data types, thereby improving code readability and maintainability. Standardization: SPL data structures conform to PHP programming specifications, ensuring consistency and interoperability across applications. SPL Data Structure Types SPL provides several data structure types, each with its own unique characteristics and uses: Stack (St

See all articles