[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.
C++
#include<iostream>#include<vector>usingnamespacestd;// To heapify a subtree voidheapify(vector<int>&arr,intn,inti){// Initialize largest as rootintlargest=i;intl=2*i+1;intr=2*i+2;// If left child is larger than rootif(l<n&&arr[l]>arr[largest])largest=l;// If right child is larger than largest so farif(r<n&&arr[r]>arr[largest])largest=r;// If largest is not rootif(largest!=i){swap(arr[i],arr[largest]);// Recursively heapify the affected sub-treeheapify(arr,n,largest);}}// Function to build a Max-Heap from the given arrayvoidbuildHeap(vector<int>&arr){intn=arr.size();// Index of last non-leaf nodeintstartIdx=(n/2)-1;// Perform reverse level order traversal// from last non-leaf node and heapify// each nodefor(inti=startIdx;i>=0;i--){heapify(arr,n,i);}}intmain(){// Binary Tree Representation// of input array// 1// / \ // 3 5// / \ / \ // 4 6 13 10// / \ / \ // 9 8 15 17vector<int>arr={1,3,5,4,6,13,10,9,8,15,17};// Function callbuildHeap(arr);for(inti=0;i<arr.size();++i)cout<<arr[i]<<" ";cout<<"\n";// Final Heap:// 17// / \ // 15 13// / \ / \ // 9 6 5 10// / \ / \ // 4 8 3 1return0;}
C
#include<stdio.h>#include<stdlib.h>// To heapify a subtree voidheapify(intarr[],intn,inti){// Initialize largest as rootintlargest=i;intl=2*i+1;intr=2*i+2;// If left child is larger than rootif(l<n&&arr[l]>arr[largest])largest=l;// If right child is larger than largest so farif(r<n&&arr[r]>arr[largest])largest=r;// If largest is not rootif(largest!=i){inttemp=arr[i];arr[i]=arr[largest];arr[largest]=temp;// Recursively heapify the affected sub-treeheapify(arr,n,largest);}}// Function to build a Max-Heap from the given arrayvoidbuildHeap(intarr[],intn){// Index of last non-leaf nodeintstartIdx=(n/2)-1;// Perform reverse level order traversal// from last non-leaf node and heapify// each nodefor(inti=startIdx;i>=0;i--){heapify(arr,n,i);}}intmain(){// Binary Tree Representation// of input array// 1// / \ // 3 5// / \ / \ // 4 6 13 10// / \ / \ // 9 8 15 17intarr[]={1,3,5,4,6,13,10,9,8,15,17};intn=sizeof(arr)/sizeof(arr[0]);// Function callbuildHeap(arr,n);for(inti=0;i<n;++i)printf("%d ",arr[i]);printf("\n");// Final Heap:// 17// / \ // 15 13// / \ / \ // 9 6 5 10// / \ / \ // 4 8 3 1return0;}
Java
publicclassGfG{// To heapify a subtree staticvoidheapify(intarr[],intn,inti){// Initialize largest as rootintlargest=i;intl=2*i+1;intr=2*i+2;// If left child is larger than rootif(l<n&&arr[l]>arr[largest])largest=l;// If right child is larger than largest so farif(r<n&&arr[r]>arr[largest])largest=r;// If largest is not rootif(largest!=i){inttemp=arr[i];arr[i]=arr[largest];arr[largest]=temp;// Recursively heapify the affected sub-treeheapify(arr,n,largest);}}// Function to build a Max-Heap from the given arraystaticvoidbuildHeap(intarr[]){intn=arr.length;// Index of last non-leaf nodeintstartIdx=(n/2)-1;// Perform reverse level order traversal// from last non-leaf node and heapify// each nodefor(inti=startIdx;i>=0;i--){heapify(arr,n,i);}}publicstaticvoidmain(String[]args){// Binary Tree Representation// of input array// 1// / \// 3 5// / \ / \// 4 6 13 10// / \ / \// 9 8 15 17intarr[]={1,3,5,4,6,13,10,9,8,15,17};intn=arr.length;// Function callbuildHeap(arr);for(inti=0;i<n;++i)System.out.print(arr[i]+" ");System.out.println();// Final Heap:// 17// / \// 15 13// / \ / \// 9 6 5 10// / \ / \// 4 8 3 1}}
Python
# To heapify a subtree defheapify(arr,n,i):# Initialize largest as rootlargest=il=2*i+1r=2*i+2# If left child is larger than rootifl<nandarr[l]>arr[largest]:largest=l# If right child is larger than largest so farifr<nandarr[r]>arr[largest]:largest=r# If largest is not rootiflargest!=i:arr[i],arr[largest]=arr[largest],arr[i]# Recursively heapify the affected sub-treeheapify(arr,n,largest)# Function to build a Max-Heap from the given arraydefbuildHeap(arr):n=len(arr)# Index of last non-leaf nodestartIdx=(n//2)-1# Perform reverse level order traversal# from last non-leaf node and heapify# each nodeforiinrange(startIdx,-1,-1):heapify(arr,n,i)if__name__=="__main__":# Binary Tree Representation# of input array# 1# / \# 3 5# / \ / \# 4 6 13 10# / \ / \# 9 8 15 17arr=[1,3,5,4,6,13,10,9,8,15,17]n=len(arr)# Function callbuildHeap(arr)foriinrange(n):print(arr[i],end=" ")print()# Final Heap:# 17# / \# 15 13# / \ / \# 9 6 5 10# / \ / \# 4 8 3 1
C#
usingSystem;classGFG{// To heapify a subtree staticvoidheapify(int[]arr,intn,inti){// Initialize largest as rootintlargest=i;intl=2*i+1;intr=2*i+2;// If left child is larger than rootif(l<n&&arr[l]>arr[largest])largest=l;// If right child is larger than largest so farif(r<n&&arr[r]>arr[largest])largest=r;// If largest is not rootif(largest!=i){inttemp=arr[i];arr[i]=arr[largest];arr[largest]=temp;// Recursively heapify the affected sub-treeheapify(arr,n,largest);}}// Function to build a Max-Heap from the given arraystaticvoidbuildHeap(int[]arr){intn=arr.Length;// Index of last non-leaf nodeintstartIdx=(n/2)-1;// Perform reverse level order traversal// from last non-leaf node and heapify// each nodefor(inti=startIdx;i>=0;i--){heapify(arr,n,i);}}staticvoidMain(){// Binary Tree Representation// of input array// 1// / \// 3 5// / \ / \// 4 6 13 10// / \ / \// 9 8 15 17int[]arr={1,3,5,4,6,13,10,9,8,15,17};intn=arr.Length;// Function callbuildHeap(arr);for(inti=0;i<n;i++)Console.Write(arr[i]+" ");Console.WriteLine();// Final Heap:// 17// / \// 15 13// / \ / \// 9 6 5 10// / \ / \// 4 8 3 1}}
JavaScript
// To heapify a subtree rooted functionheapify(arr,n,i){letlargest=i;letl=2*i+1;letr=2*i+2;// If left child is larger than rootif(l<n&&arr[l]>arr[largest])largest=l;// If right child is larger than largest so farif(r<n&&arr[r]>arr[largest])largest=r;// If largest is not rootif(largest!==i){[arr[i],arr[largest]]=[arr[largest],arr[i]];// Recursively heapify the affected sub-treeheapify(arr,n,largest);}}// Function to build a Max-Heap from the given arrayfunctionbuildHeap(arr){constn=arr.length;// Index of last non-leaf nodeletstartIdx=Math.floor(n/2)-1;// Perform reverse level order traversal// from last non-leaf node and heapify// each nodefor(leti=startIdx;i>=0;i--){heapify(arr,n,i);}}// Driver Code// Binary Tree Representation of input array// 1// / \// 3 5// / \ / \// 4 6 13 10// / \ / \// 9 8 15 17constarr=[1,3,5,4,6,13,10,9,8,15,17];constn=arr.length;// Build Max HeapbuildHeap(arr);for(leti=0;i<n;i++)process.stdout.write(arr[i]+" ");console.log("\n");// Final Heap Representation// 17// / \// 15 13// / \ / \// 9 6 5 10// / \ / \// 4 8 3 1