Heap operations

As we have mentioned a few times that heap is a specialized tree data structure, we have to make sure that we first construct a heap from a given list of items. As heap has a strict heap property, we have to satisfy the heap property on each step. Here are some of the core operations for heap:

  • Create heap
  • Insert a new value
  • Extract minimum or maximum from heap
  • Remove a value
  • Swapping

Creating a heap from a given list of items or numbers requires us to ensure that both heap property and binary tree property are satisfied. Which means the parent node must be greater or less than the child nodes and that will be true for all nodes in the tree. Also the tree must be a complete binary tree all the time. While creating a heap, we start with one node and insert a new node to the heap.

The insert node operation has a defined set of steps. We cannot start from an arbitrary node. The steps for insert operation are as follows:

  1. Insert the new node at the bottom of the heap.
  2. Check the new node with parent value if they are in the right order. If they are in the right order, stop there.
  3. If they are not in the right order, swap them and move to the previous step to check the newly swapped node with its parent node. This step along with the previous one is known as sift up or up-heap, or bubble-up, or heapify-up, and so on.

The extract operation (minimum or maximum) takes out the root node from the heap. After this we have to do the following operations to ensure heap properties for the remaining heap:

  1. Move the last node from the heap as the new root.
  2. Compare the new root node with the child nodes, if they are in the correct order, stop.
  3. If not, swap the root node with the child node (minimum child for MinHeap, maximum child for MaxHeap) and continue with the previous step. This step along with the previous one is known as sift down or down-heap, or bubble-down or heapify-down, and so on.

In heap, one of the important operations is swapping. In many cases, we have to swap two values from two nodes without impacting the tree's properties. Now we are going to implement a binary heap using PHP 7.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset