How to build a max heap using an array
A heap is a binary tree that meets the heap property. Heap can be of two types:
Min heap: The value of each node is larger than or equal to the value of its parent. The node with the lowest value is the root.
Max heap: Each node's value is smaller than its parent's value. The highest value element is at the root.
Building a heap from an array ensures that the heap order property is maintained after every input. For max heap, the newly entered value is checked whether it is smaller than its parent. If it's not, it is swapped.
How to represent a binary tree as an array
The root is at index 0 in the array.
The left child of the ith node is at (
)th index. The right child of the ith node is at (
)th index. The parent of the ith node is at
th index.
Let's take a look at an example. Consider the following max heap:
The array representation of the max heap above is as follows:
Build max heap from the array
Let's see how we build max heap from a given array. Here we consider a random array. First, we create a binary tree of the array. Then, starting from the leaf nodes, we swap the nodes based on their values.
The technique transfers the smallest node to the leaf nodes and the largest node towards the root. The values are swapped until the element of each node is less than the element at its parent. Let's visualize it:
Example
Here's the step-by-step implementation of building a heap from a given array:
#include <iostream>using namespace std;int size; // size of arrayvoid heapify(int array[], int i){int large = i; // The node which will be heapifiedint left = (2 * i) + 1; // left child nodeint right = (2 * i) + 2; // right child node// Check if left child is largerif (left < size && array[left] > array[large])large = left;// Check if right child is largerif (right < size && array[right] > array[large])large = right;// If largest is not parentif (large != i) {swap(array[i], array[large]);// Recursively changed sub-treeheapify(array, large);}}void build_heap(int array[]){// heapify each node of arrayfor (int i = size; i >= 0; i--) {heapify(array, i);}}// Driver Codeint main(){int array[] = { 1, 5, 6, 8, 9, 7, 3};size = sizeof(array) / sizeof(array[0]); //sizecout << "Sample Array : ";for (int i = 0; i < size; ++i) //loop for printing arraycout << array[i] << " ";cout <<endl;//calling heap functionbuild_heap(array);cout << "Heapify Array: ";for (int i = 0; i < size; ++i) //loop for printing heapcout << array[i] << " ";return 0;}
Explanation
Line 5–11: We define a
sizevariable and aheapify()function. We declare thelarge,left, andrightvariables to keep track of nodes.Line 14–19: We check the given value whether it is greater than the
leftandrightchild.Line 22–26: If a parent is not the largest, the values are swapped, and the affected subtree is again called in the
heapify()function.Line 30–36: Each value is called in the
heapify()function using aforloop.
Time Complexity
It takes
Free Resources