VOOZH about

URL: https://www.geeksforgeeks.org/dsa/building-heap-from-array/

⇱ Building Heap from Array - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Building Heap from Array

Last Updated : 18 Oct, 2025

Given an integer array arr[], build a Max Heap from the given array.

A Max Heap is a complete binary tree where each parent node is greater than or equal to its children, ensuring the largest element is at the root.

Examples:

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

👁 420046828


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

👁 420046829

[Approach] Using Recursion - O(n) Time and O(log n) Space

To build a Max Heap from an array, treat the array as a complete binary tree and heapify nodes from the last non-leaf node up to the root in reverse level order. Leaf nodes already satisfy the heap property, so we start from the last non-leaf node, and for each subtree, we compare the parent with its children. Whenever a child node is greater than the parent, we swap them and continue heapifying that subtree to ensure the Max Heap property is maintained throughout.

Note :

  • Root is at index 0.
  • Left child of node i -> 2*i + 1.
  • Right child of node i -> 2*i + 2.
  • Parent of node i -> (i-1)/2.
  • Last non-leaf node -> parent of last node -> (n/2) - 1.



Output
17 15 13 9 6 5 10 4 8 3 1 
Comment
Article Tags:
Article Tags: