Heap Data Structure
In this lecture, we will learn what heap data structure is.
Heap data structure is a complete binary tree that satisfies the heap property, where any given
node is
always greater than its child node/s and the key of the root node is the largest among all other
nodes. This property is also called max heap property.
always smaller than the child node/s and the key of the root node is the smallest among all
other nodes. This property is also called min heap property.
Max Heap
Min Heap
This type of data structure is also called a binary heap.
Heap Operations
Some of the important operations performed on a heap are described below along with their
algorithms.
Heapify
Heapify is the process of creating a heap data structure from a binary tree. It is used to create a
Min-Heap or a Max-Heap.
1. Let the input array be
Initial Array
2. Create a complete binary tree from the array
Complete binary tree
3. Start from the first index of non-leaf node whose index is given by n/2 - 1.
Start from the first on leaf node
4. Set current element i as largest.
5. The index of left child is given by 2i + 1 and the right child is given by 2i + 2.
If left Child is greater than current Element (i.e. element at ith index),set left Child
Index as largest.
If right Child is greater than element in largest, set right Child Index as largest.
6. Swap largest with current Element
Swap if necessary
7. Repeat steps 3-7 until the subtrees are also heapified.