Given an array of n elements. The task is to build a Max Heap from the given array.
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.
The idea is to heapify the complete binary tree formed from the array from the last node to root (in reverse level order traversal manner). We can optimize it by observing the fact that the leaf nodes need not to be heapified as they already follow the heap property. So the idea is to find the position of the last non-leaf node and do heapify of each non-leaf node in reverse level order.
How do we find the index of the last non-leaf node?
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.
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;
}
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;
}
Java
// Java program for building Heap from Array
import java.util.Arrays;
public class GfG {
// To heapify a subtree rooted with node i which is
// an index in arr[]. N 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 given 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;
// Function call
buildHeap(arr, n);
printHeap(arr, n);
// Final Heap:
// 17
// / \
// 15 13
// / \ / \
// 9 6 5 10
// / \ / \
// 4 8 3 1
}
}
Python
# 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 = 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 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)
# Function call
buildHeap(arr, n)
printHeap(arr, n)
# Final Heap:
# 17
# / \
# 15 13
# / \ / \
# 9 6 5 10
# / \ / \
# 4 8 3 1
C#
// 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) {
int temp = arr[i];
arr[i] = arr[largest];
arr[largest] = temp;
// 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)
{
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;
// Function call
BuildHeap(arr, n);
PrintHeap(arr);
// Final Heap:
// 17
// / \
// 15 13
// / \ / \
// 9 6 5 10
// / \ / \
// 4 8 3 1
}
JavaScript
// To heapify a subtree rooted with node i which is
// an index in arr[]. N is size of heap
function heapify(arr, n, i) {
let largest = i; // Initialize largest as root
let l = 2 * i + 1; // left = 2*i + 1
let 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) {
[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
function buildHeap(arr, n) {
// Index of last non-leaf node
let startIdx = Math.floor(n / 2) - 1;
// Perform reverse level order traversal
// from last non-leaf node and heapify
// each node
for (let i = startIdx; i >= 0; i--) {
heapify(arr, n, i);
}
}
// A utility function to print the array
// representation of Heap
function printHeap(arr, n) {
console.log("Array representation of Heap is:");
for (let i = 0; i < n; ++i)
process.stdout.write(arr[i] + " ");
console.log("\n");
}
// Driver Code
const arr = [1, 3, 5, 4, 6, 13, 10, 9, 8, 15, 17];
const n = arr.length;
// Function call
buildHeap(arr, n);
printHeap(arr, n);
// Final Heap:
// 17
// / \
// 15 13
// / \ / \
// 9 6 5 10
// / \ / \
// 4 8 3 1
OutputArray representation of Heap is:
17 15 13 9 6 5 10 4 8 3 1
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
Similar Reads
Heap Sort - Data Structures and Algorithms Tutorials Heap sort is a comparison-based sorting technique based on Binary Heap Data Structure. It can be seen as an optimization over selection sort where we first find the max (or min) element and swap it with the last (or first). We repeat the same process for the remaining elements. In Heap Sort, we use
14 min read
Iterative HeapSort HeapSort is a comparison-based sorting technique where we first build Max Heap and then swap the root element with the last element (size times) and maintains the heap property each time to finally make it sorted. Examples: Input : 10 20 15 17 9 21 Output : 9 10 15 17 20 21 Input: 12 11 13 5 6 7 15
11 min read
Java Program for Heap Sort Heap sort is a comparison-based sorting technique based on the Binary Heap data structure. It is similar to the selection sort where first find the maximum element and place it at the end. We repeat the same process for the remaining element. Heap Sort in JavaBelow is the implementation of Heap Sort
3 min read
C++ Program for Heap Sort Heap sort is a comparison-based sorting technique based on the Binary Heap data structure. It is similar to the selection sort where we first find the maximum element and place the maximum element at the end. We repeat the same process for the remaining element. Recommended PracticeHeap SortTry It!
3 min read
sort_heap function in C++ The sort_heap( ) is an STL algorithm which sorts a heap within the range specified by start and end. Sorts the elements in the heap range [start, end) into ascending order. The second form allows you to specify a comparison function that determines when one element is less than another. Defined in h
3 min read
Heap Sort - Python Heapsort is a comparison-based sorting technique based on a Binary Heap data structure. It is similar to selection sort where we first find the maximum element and place the maximum element at the end. We repeat the same process for the remaining element.Heap Sort AlgorithmFirst convert the array in
4 min read
Lexicographical ordering using Heap Sort Given an array arr[] of strings. The task is to sort the array in lexicographical order using Heap Sort.Examples: Input: arr[] = { "banana", "apple", "mango", "pineapple", "orange" } Output: apple banana mango orange pineappleInput: arr[] = { "CAB", "ACB", "ABC", "CBA", "BAC" } Output: ABC, ACB, BAC
10 min read
Heap sort for Linked List Given a linked list, the task is to sort the linked list using HeapSort. Examples: Input: list = 7 -> 698147078 -> 1123629290 -> 1849873707 -> 1608878378 -> 140264035 -> -1206302000Output: -1206302000 -> 7 -> 140264035 -> 1123629290 -> 1608878378 -> 1698147078 ->1
14 min read
Python Code for time Complexity plot of Heap Sort Prerequisite : HeapSort Heap sort is a comparison based sorting technique based on Binary Heap data structure. It is similar to selection sort where we first find the maximum element and place the maximum element at the end. We repeat the same process for remaining element. We implement Heap Sort he
3 min read
Sorting algorithm visualization : Heap Sort An algorithm like Heap sort can be understood easily by visualizing. In this article, a program that visualizes the Heap Sort Algorithm has been implemented. The Graphical User Interface(GUI) is implemented in Python using pygame library. Approach: Generate random array and fill the pygame window wi
4 min read