From the course: Learning the Standard PHP Library

Unlock the full course today

Join today to access over 22,500 courses taught by industry experts or purchase this course individually.

Understanding heaps

Understanding heaps - PHP Tutorial

From the course: Learning the Standard PHP Library

Start my 1-month free trial

Understanding heaps

Several SPL data structures are based on heaps. A heap is a binary tree structure in which each node has zero, one, or two children. The root node contains the lowest or highest value, depending on how the heap has been constructed. When the root node contains the lowest value, it's called a min heap and the value of each parent node is always smaller than its children. The opposite is a max heap, where the value of the parent node is always larger than either of its children. The only value that's in a predictable position is the one at the top of the heap, the biggest value in a max heap, and the smallest value in a min heap. These examples use numbers, but a heap can store any type of data. Although the chaotic order inside the binary tree sounds inefficient, heaps are, in fact, very efficient, particularly for storing and sorting many items. New items are added at the bottom of the heap. 12 has just been added as the right-hand child of the node that contains the number nine. This…

Contents