Skip to content
Related Articles

Related Articles

Building Heap from Array

View Discussion
Improve Article
Save Article
  • Difficulty Level : Medium
  • Last Updated : 10 Aug, 2022

Given an array of N elements. The task is to build a Binary Heap from the given array. The heap can be either Max Heap or Min Heap.

Examples: 

Input: arr[] = {4, 10, 3, 5, 1}
Output: Corresponding Max-Heap:

       10
     /   \
   5     3
  /  \
4    1

Input: arr[] = {1, 3, 5, 4, 6, 13, 10, 9, 8, 15, 17}
Output: Corresponding Max-Heap:

                 17
              /      \
          15         13
         /    \      /  \
       9      6    5   10
     / \    /  \
   4   8  3    1

Note:

  • Root is at index 0 in array.
  • Left child of i-th node is at (2*i + 1)th index.
  • Right child of i-th node is at (2*i + 2)th index.
  • Parent of i-th node is at (i-1)/2 index.
 

Complete Interview Preparation - GFG

Naive Approach:  To solve the problem follow the below idea:

To build a Max-Heap from the above-given array elements, It can be clearly seen that the above complete binary tree formed does not follow the Heap property. So, the idea is to heapify the complete binary tree formed from the array in reverse level order following a top-down approach. That is first heapify, the last node in level order traversal of the tree, then heapify the second last node and so on. 

Time Complexity Analysis: Heapify a single node takes O(log N) time complexity where N is the total number of Nodes. Therefore, building the entire Heap will take N heapify operations and the total time complexity will be O(N*logN).
Note: In reality, building a heap takes O(n) time depending on the implementation which can be seen here

Efficient Approach: To solve the problem using this approach follow the below idea:

The above approach can be optimized by observing the fact that the leaf nodes need not to be heapified as they already follow the heap property. Also, the array representation of the complete binary tree contains the level order traversal of the tree. So the idea is to find the position of the last non-leaf node and perform the heapify operation of each non-leaf node in reverse level order. 
 

Last non-leaf node = parent of last-node.
or, Last non-leaf node = parent of node at (n-1)th index.
or, Last non-leaf node = Node at index ((n-1) – 1)/2 = (n/2) – 1.

Heapify Illustration: 
 

Array = {1, 3, 5, 4, 6, 13, 10, 9, 8, 15, 17}
Corresponding Complete Binary Tree is:

                 1
              /     \
           3         5
        /    \     /  \
      4      6   13  10
     / \    / \
   9   8  15 17

The task to build a Max-Heap from above array.

Total Nodes = 11.
Last Non-leaf node index = (11/2) – 1 = 4.
Therefore, last non-leaf node = 6.

To build the heap, heapify only the nodes: [1, 3, 5, 4, 6] in reverse order.

Heapify 6: Swap 6 and 17.

                 1
              /     \
           3         5
        /    \      /  \
     4      17   13  10
    / \    /  \
  9   8  15   6

Heapify 4: Swap 4 and 9.

                 1
              /     \
           3         5
        /    \      /  \
     9      17   13  10
    / \    /  \
  4   8  15   6

Heapify 5: Swap 13 and 5.

                 1
              /     \
           3         13
        /    \      /  \
     9      17   5   10
    / \    /  \
 4   8  15   6

Heapify 3: First Swap 3 and 17, again swap 3 and 15.

                 1
             /     \
        17         13
       /    \      /  \
    9      15   5   10
   / \    /  \
 4   8  3   6

Heapify 1: First Swap 1 and 17, again swap 1 and 15, finally swap 1 and 6.

                 17
              /      \
          15         13
         /    \      /  \
       9      6    5   10
      / \    /  \
    4   8  3    1

Below is the implementation of the above approach:
 

C




// C program for building Heap from Array
 
#include <stdio.h>
 
// To heapify a subtree rooted with node i which is
// an index in arr[]. N is size of heap
void swap(int *a, int *b)
{
    int tmp = *a;
      *a = *b;
      *b = tmp;
}
 
void heapify(int arr[], int N, int i)
{
    int largest = i; // Initialize largest as root
    int l = 2 * i + 1; // left = 2*i + 1
    int r = 2 * i + 2; // right = 2*i + 2
 
    // If left child is larger than root
    if (l < N && arr[l] > arr[largest])
        largest = l;
 
    // If right child is larger than largest so far
    if (r < N && arr[r] > arr[largest])
        largest = r;
 
    // If largest is not root
    if (largest != i) {
        swap(&arr[i], &arr[largest]);
 
        // Recursively heapify the affected sub-tree
        heapify(arr, N, largest);
    }
}
 
// Function to build a Max-Heap from the given array
void buildHeap(int arr[], int N)
{
    // Index of last non-leaf node
    int startIdx = (N / 2) - 1;
 
    // Perform reverse level order traversal
    // from last non-leaf node and heapify
    // each node
    for (int i = startIdx; i >= 0; i--) {
        heapify(arr, N, i);
    }
}
 
// A utility function to print the array
// representation of Heap
void printHeap(int arr[], int N)
{
    printf("Array representation of Heap is:\n");
 
    for (int i = 0; i < N; ++i)
        printf("%d ",arr[i]);
    printf("\n");
}
 
// Driver's Code
int main()
{
    // Binary Tree Representation
    // of input array
    //             1
    //           /    \
    //         3        5
    //       /  \     /  \
    //     4      6  13  10
    //    / \    / \
    //   9   8  15 17
    int arr[] = {1, 3, 5, 4, 6, 13, 10, 9, 8, 15, 17};
 
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // Function call
    buildHeap(arr, N);
    printHeap(arr, N);
   
    // Final Heap:
    //              17
    //            /    \
    //          15      13
    //         /  \     / \
    //        9     6  5   10
    //       / \   / \
    //      4   8 3   1
 
    return 0;
}

C++




// C++ program for building Heap from Array
 
#include <bits/stdc++.h>
 
using namespace std;
 
// To heapify a subtree rooted with node i which is
// an index in arr[]. N is size of heap
void heapify(int arr[], int N, int i)
{
    int largest = i; // Initialize largest as root
    int l = 2 * i + 1; // left = 2*i + 1
    int r = 2 * i + 2; // right = 2*i + 2
 
    // If left child is larger than root
    if (l < N && arr[l] > arr[largest])
        largest = l;
 
    // If right child is larger than largest so far
    if (r < N && arr[r] > arr[largest])
        largest = r;
 
    // If largest is not root
    if (largest != i) {
        swap(arr[i], arr[largest]);
 
        // Recursively heapify the affected sub-tree
        heapify(arr, N, largest);
    }
}
 
// Function to build a Max-Heap from the given array
void buildHeap(int arr[], int N)
{
    // Index of last non-leaf node
    int startIdx = (N / 2) - 1;
 
    // Perform reverse level order traversal
    // from last non-leaf node and heapify
    // each node
    for (int i = startIdx; i >= 0; i--) {
        heapify(arr, N, i);
    }
}
 
// A utility function to print the array
// representation of Heap
void printHeap(int arr[], int N)
{
    cout << "Array representation of Heap is:\n";
 
    for (int i = 0; i < N; ++i)
        cout << arr[i] << " ";
    cout << "\n";
}
 
// Driver Code
int main()
{
    // Binary Tree Representation
    // of input array
    //             1
    //           /    \
    //         3        5
    //       /  \     /  \
    //     4      6  13  10
    //    / \    / \
    //   9   8  15 17
    int arr[] = {1, 3, 5, 4, 6, 13, 10, 9, 8, 15, 17};
 
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // Function call
    buildHeap(arr, N);
    printHeap(arr, N);
   
    // Final Heap:
    //              17
    //            /    \
    //          15      13
    //         /  \     / \
    //        9     6  5   10
    //       / \   / \
    //      4   8 3   1
 
    return 0;
}

Java




// Java program for building Heap from Array
 
public class BuildHeap {
 
    // To heapify a subtree rooted with node i which is
    // an index in arr[].Nn is size of heap
    static void heapify(int arr[], int N, int i)
    {
        int largest = i; // Initialize largest as root
        int l = 2 * i + 1; // left = 2*i + 1
        int r = 2 * i + 2; // right = 2*i + 2
 
        // If left child is larger than root
        if (l < N && arr[l] > arr[largest])
            largest = l;
 
        // If right child is larger than largest so far
        if (r < N && arr[r] > arr[largest])
            largest = r;
 
        // If largest is not root
        if (largest != i) {
            int swap = arr[i];
            arr[i] = arr[largest];
            arr[largest] = swap;
 
            // Recursively heapify the affected sub-tree
            heapify(arr, N, largest);
        }
    }
 
    // Function to build a Max-Heap from the Array
    static void buildHeap(int arr[], int N)
    {
        // Index of last non-leaf node
        int startIdx = (N / 2) - 1;
 
        // Perform reverse level order traversal
        // from last non-leaf node and heapify
        // each node
        for (int i = startIdx; i >= 0; i--) {
            heapify(arr, N, i);
        }
    }
 
    // A utility function to print the array
    // representation of Heap
    static void printHeap(int arr[], int N)
    {
        System.out.println(
            "Array representation of Heap is:");
 
        for (int i = 0; i < N; ++i)
            System.out.print(arr[i] + " ");
 
        System.out.println();
    }
 
    // Driver Code
    public static void main(String args[])
    {
        // Binary Tree Representation
        // of input array
        //            1
        //         /      \
        //       3        5
        //     /   \       / \
        //  4       6  13 10
        // / \    /  \
        // 9  8  15   17
        int arr[] = {1, 3, 5, 4, 6, 13, 10, 9, 8, 15, 17};
        int N = arr.length;
       
        buildHeap(arr, N);
        printHeap(arr, N);
    }
}

Python3




# Python3 program for building Heap from Array
 
# To heapify a subtree rooted with node i
# which is an index in arr[]. N is size of heap
 
def heapify(arr, N, i):
 
    largest = # Initialize largest as root
    l = 2 * i + 1  # left = 2*i + 1
    r = 2 * i + 2  # right = 2*i + 2
 
    # If left child is larger than root
    if l < N and arr[l] > arr[largest]:
        largest = l
 
    # If right child is larger than largest so far
    if r < N and arr[r] > arr[largest]:
        largest = r
 
    # If largest is not root
    if largest != i:
        arr[i], arr[largest] = arr[largest], arr[i]
 
        # Recursively heapify the affected sub-tree
        heapify(arr, N, largest)
 
# Function to build a Max-Heap from the given array
 
 
def buildHeap(arr, N):
 
    # Index of last non-leaf node
    startIdx = N // 2 - 1
 
    # Perform reverse level order traversal
    # from last non-leaf node and heapify
    # each node
    for i in range(startIdx, -1, -1):
        heapify(arr, N, i)
 
# A utility function to print the array
# representation of Heap
 
 
def printHeap(arr, N):
    print("Array representation of Heap is:")
 
    for i in range(N):
        print(arr[i], end=" ")
    print()
 
 
# Driver Code
if __name__ == '__main__':
 
    # Binary Tree Representation
    # of input array
    #             1
    #           /    \
    #         3        5
    #       /  \     /  \
    #     4      6  13  10
    #    / \    / \
    #   9   8  15 17
    arr = [1, 3, 5, 4, 6, 13,
           10, 9, 8, 15, 17]
 
    N = len(arr)
 
    buildHeap(arr, N)
    printHeap(arr, N)
 
    # Final Heap:
    #             17
    #           /    \
    #         15      13
    #        /  \     / \
    #       9     6  5   10
    #      / \   / \
    #     4   8 3   1
 
# This code is contributed by Princi Singh

C#




// C# program for building Heap from Array
using System;
 
public class BuildHeap {
 
    // To heapify a subtree rooted with node i which is
    // an index in arr[].Nn is size of heap
    static void heapify(int[] arr, int N, int i)
    {
        int largest = i; // Initialize largest as root
        int l = 2 * i + 1; // left = 2*i + 1
        int r = 2 * i + 2; // right = 2*i + 2
 
        // If left child is larger than root
        if (l < N && arr[l] > arr[largest])
            largest = l;
 
        // If right child is larger than largest so far
        if (r < N && arr[r] > arr[largest])
            largest = r;
 
        // If largest is not root
        if (largest != i) {
            int swap = arr[i];
            arr[i] = arr[largest];
            arr[largest] = swap;
 
            // Recursively heapify the affected sub-tree
            heapify(arr, N, largest);
        }
    }
 
    // Function to build a Max-Heap from the Array
    static void buildHeap(int[] arr, int N)
    {
        // Index of last non-leaf node
        int startIdx = (N / 2) - 1;
 
        // Perform reverse level order traversal
        // from last non-leaf node and heapify
        // each node
        for (int i = startIdx; i >= 0; i--) {
            heapify(arr, N, i);
        }
    }
 
    // A utility function to print the array
    // representation of Heap
    static void printHeap(int[] arr, int N)
    {
        Console.WriteLine(
            "Array representation of Heap is:");
 
        for (int i = 0; i < N; ++i)
            Console.Write(arr[i] + " ");
 
        Console.WriteLine();
    }
 
    // Driver Code
    public static void Main()
    {
        // Binary Tree Representation
        // of input array
        //            1
        //         /      \
        //       3        5
        //      /  \       / \
        //   4       6  13 10
        //  / \   / \
        // 9   8 15  17
        int[] arr = {1, 3, 5, 4, 6, 13, 10, 9, 8, 15, 17};
 
        int N = arr.Length;
 
        buildHeap(arr, N);
 
        printHeap(arr, N);
    }
}
 
// This code is contributed by Ryuga

PHP




<?php
     
function heapify(&$arr, $N, $i)
{
    $largest = $i; // Initialize largest as root
    $l = 2*$i + 1; // left = 2*i + 1
    $r = 2*$i + 2; // right = 2*i + 2
  
    // If left child is larger than root
    if ($l < $N && $arr[$l] > $arr[$largest])
        $largest = $l;
  
    // If right child is larger than largest so far
    if ($r < $N && $arr[$r] > $arr[$largest])
        $largest = $r;
  
    // If largest is not root
    if ($largest != $i)
    {
        $swap = $arr[$i];
        $arr[$i] = $arr[$largest];
        $arr[$largest] = $swap;
  
        // Recursively heapify the affected sub-tree
        heapify($arr, $N, $largest);
    }
}
 
function buildHeap(&$arr, $N)
{
    // Build heap (rearrange array)
    for ($i = ($N / 2) - 1; $i >= 0; $i--)
        heapify($arr, $N, $i);
}
 
function printArray(&$arr, $N)
{
    for ($i = 0; $i < $N; ++$i)
        echo ($arr[$i]." ") ;
}
 
// Driver's code
     $arr = array(1, 3, 5, 4, 6, 13, 10, 9, 8, 15, 17);
    $N = sizeof($arr)/sizeof($arr[0]);
  
    buildHeap($arr, $N);
  
    echo 'Array representation of Heap is:' . "\n";
     
    printArray($arr , $N);
?>

Javascript




// Javascript code for the above approach
 
function heapify(arr, N, i)
{
    var largest = i; // Initialize largest as root
    var l = 2 * i + 1; // left = 2*i + 1
    var r = 2 * i + 2; // right = 2*i + 2
  
    // If left child is larger than root
    if (l < N && arr[l] > arr[largest])
        largest = l;
  
    // If right child is larger than largest so far
    if (r < N && arr[r] > arr[largest])
        largest = r;
  
    // If largest is not root
     if (largest != i) {
        var swap = arr[i];
        arr[i] = arr[largest];
        arr[largest] = swap;
  
        // Recursively heapify the affected sub-tree
        heapify(arr, N, largest);
    }
}
 
function buildHeap( arr)
{
    var N = arr.length;
  
    // Build heap (rearrange array)
    for (var i = Math.floor(N / 2) - 1; i >= 0; i--)
        heapify(arr, N, i);
}
 
function printArray(arr)
{
    var N = arr.length;
    for (var i = 0; i < N; ++i)
        document.write(arr[i] + " ");
          
}
  
 // Driver's code
 var arr = [1, 3, 5, 4, 6, 13, 10, 9, 8, 15, 17];
 var N = arr.length;
  
 // Function call
 buildHeap(arr)
  
 document.write( "Array representation of Heap is: ");
 printArray(arr, N);

Output

Array representation of Heap is:
17 15 13 9 6 5 10 4 8 3 1 

Time Complexity: O(N)
Auxiliary Space: O(N)


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!