A Max-Heap is a Data Structure with the following properties:
- It is a Complete Binary Tree.
- The value of the root node must be the largest among all its descendant nodes, and the same property must hold for its left and right subtrees.
Implementation of Max-Heap Data Structure
A heap can be efficiently represented using an array.
If a node is stored at index i:
- Its left child is at index 2 * i + 1.
- Its right child is at index 2 * i + 2.
- The parent of a node at index i can be found at index [(i-1)/2].
Operations on Max-heap Data Structure and their Implementation
Here are some common operations that can be performed on a Heap Data Structure data structure,
Insertion - O(log n) Time and O(n) Space
Insertion in a Max-Heap involves the following steps:
- Add the new element to the end of the heap, in the next available position in the last level of the tree.
- Compare the new element with its parent. If the parent is smaller than the new element, swap them.
- Repeat step 2 until the parent is greater than or equal to the new element, or until the new element reaches the root of the tree.
Illustration:
C++
#include <iostream>
#include <vector>
using namespace std;
void insert(vector<int>& heap, int value)
{
// Add the new element to the end of the heap
heap.push_back(value);
// Get the index of the last element
int index = heap.size() - 1;
// Compare the new element with
// its parent and swap if necessary
while (index > 0
&& heap[(index - 1) / 2] < heap[index]) {
swap(heap[index], heap[(index - 1) / 2]);
// Move up the tree to the
// parent of the current element
index = (index - 1) / 2;
}
}
int main()
{
vector<int> arr;
vector<int>values = { 10, 7, 11, 5, 4, 13 };
int n = values.size();
for (int i = 0; i < n; i++) {
insert(arr, values[i]);
cout << "Inserted " << values[i]
<< " into the max-heap: ";
for (int j = 0; j < arr.size(); j++) {
cout << arr[j] << " ";
}
cout << endl;
}
return 0;
}
Java
import java.util.ArrayList;
public class GFG {
public static void insert(ArrayList<Integer> heap, int value) {
// Add the new element to the end of the heap
heap.add(value);
// Get the index of the last element
int index = heap.size() - 1;
// Compare the new element with its parent and swap if necessary
while (index > 0 && heap.get((index - 1) / 2) < heap.get(index)) { // max-heap
int temp = heap.get(index);
heap.set(index, heap.get((index - 1) / 2));
heap.set((index - 1) / 2, temp);
// Move up the tree to the parent of the current element
index = (index - 1) / 2;
}
}
public static void main(String[] args) {
ArrayList<Integer> arr = new ArrayList<>();
int[] values = {10, 7, 11, 5, 4, 13};
for (int value : values) {
insert(arr, value);
System.out.print("Inserted " + value + " into the max-heap: ");
for (int i = 0; i < arr.size(); i++) {
System.out.print(arr.get(i) + " ");
}
System.out.println();
}
}
}
Python
def insert(heap, value):
# Add the new element to the end of the heap
heap.append(value)
# Get the index of the last element
index = len(heap) - 1
# Compare the new element
#with its parent and swap if necessary
while index > 0 and heap[(index - 1) // 2] < heap[index]:
heap[index], heap[(index - 1) // 2] = heap[(index - 1) // 2], heap[index]
# Move up the tree to the parent of the current element
index = (index - 1) // 2
if __name__ == "__main__":
arr = []
values = [10, 7, 11, 5, 4, 13]
for value in values:
insert(arr, value)
print(f"Inserted {value} into the max-heap: ", end="")
for v in arr:
print(v, end=" ")
print()
C#
using System;
using System.Collections.Generic;
class GFG
{
static void insert(List<int> heap, int value)
{
// Add the new element to the end of the heap
heap.Add(value);
// Get the index of the last element
int index = heap.Count - 1;
// Compare the new element with its parent and swap if necessary
while (index > 0 && heap[(index - 1) / 2] < heap[index]) // max-heap
{
int temp = heap[index];
heap[index] = heap[(index - 1) / 2];
heap[(index - 1) / 2] = temp;
// Move up the tree to the parent of the current element
index = (index - 1) / 2;
}
}
static void Main()
{
List<int> arr = new List<int>();
int[] values = { 10, 7, 11, 5, 4, 13 };
foreach (int value in values)
{
insert(arr, value);
Console.Write("Inserted " + value + " into the max-heap: ");
foreach (int v in arr)
{
Console.Write(v + " ");
}
Console.WriteLine();
}
}
}
JavaScript
function insert(heap, value) {
// Add the new element to the end of the heap
heap.push(value);
// Get the index of the last element
let index = heap.length - 1;
// Compare the new element with its parent and swap if necessary
while (index > 0 && heap[Math.floor((index - 1) / 2)] < heap[index]) {
[heap[index], heap[Math.floor((index - 1) / 2)]] = [heap[Math.floor((index - 1) / 2)], heap[index]];
// Move up the tree to the parent of the current element
index = Math.floor((index - 1) / 2);
}
}
// Driver code
const arr = [];
const values = [10, 7, 11, 5, 4, 13];
for (const value of values) {
insert(arr, value);
console.log(`Inserted ${value} into the max-heap: ${arr.join(' ')}`);
}
OutputInserted 10 into the max-heap: 10
Inserted 7 into the max-heap: 10 7
Inserted 11 into the max-heap: 11 7 10
Inserted 5 into the max-heap: 11 7 10 5
Inserted 4 into the max-heap: 11 7 10 5 4
Inser...
Deletion - O(log n) Time and O(n) Space
Removing the largest element (the root) from a Max-Heap involves the following steps:
- Replace the root (or the element to be deleted) with the last element in the heap.
- Remove the last element from the heap, since it has been moved to the root.
- Heapify-down: The element now at the root may violate the Max-Heap property, so perform heapify starting from the root to restore the heap property.
Illustration:
C++
#include <iostream>
#include <vector>
using namespace std;
void insert(vector<int>& heap, int value)
{
// Add the new element to the end of the heap
heap.push_back(value);
// Get the index of the last element
int index = heap.size() - 1;
// Compare the new element with its parent and swap if necessary
while (index > 0
&& heap[(index - 1) / 2] < heap[index]) {
swap(heap[index], heap[(index - 1) / 2]);
// Move up the tree to the parent of the current element
index = (index - 1) / 2;
}
}
// Function to delete a node from the max-heap
void deleteMax(vector<int>& heap, int value)
{
// Find the index of the element to be deleted
int index = -1;
for (int i = 0; i < heap.size(); i++) {
if (heap[i] == value) {
index = i;
break;
}
}
// If the element is not found, return
if (index == -1) {
return;
}
// Replace the element to be deleted with the last element
heap[index] = heap[heap.size() - 1];
// Remove the last element
heap.pop_back();
// Heapify the tree starting from the element at the deleted index
while (true) {
int left_child = 2 * index + 1;
int right_child = 2 * index + 2;
int largest = index;
if (left_child < heap.size() && heap[left_child] > heap[largest]) {
largest = left_child;
}
if (right_child < heap.size() && heap[right_child] > heap[largest]) {
largest = right_child;
}
if (largest != index) {
swap(heap[index], heap[largest]);
index = largest;
} else {
break;
}
}
}
int main()
{
vector<int> arr;
vector<int>values = { 13, 16, 31, 41, 51, 100 };
int n = values.size();
for (int i = 0; i < n; i++) {
insert(arr, values[i]);
}
cout << "Initial heap: ";
for (int j = 0; j < arr.size(); j++) {
cout << arr[j] << " ";
}
cout << endl;
deleteMax(arr, 13);
cout << "Heap after deleting 13: ";
for (int j = 0; j < arr.size(); j++) {
cout << arr[j] << " ";
}
cout << endl;
return 0;
}
Java
import java.util.ArrayList;
public class GFG {
// Function to insert an element into the max-heap
static void insert(ArrayList<Integer> heap, int value) {
// Add the new element to the end of the heap
heap.add(value);
// Get the index of the last element
int index = heap.size() - 1;
// Compare the new element with its parent and swap if necessary
while (index > 0 && heap.get((index - 1) / 2) < heap.get(index)) { // max-heap
int temp = heap.get(index);
heap.set(index, heap.get((index - 1) / 2));
heap.set((index - 1) / 2, temp);
// Move up the tree to the parent of the current element
index = (index - 1) / 2;
}
}
// Function to delete a node from the max-heap
static void deleteMax(ArrayList<Integer> heap, int value) {
// Find the index of the element to be deleted
int index = -1;
for (int i = 0; i < heap.size(); i++) {
if (heap.get(i) == value) {
index = i;
break;
}
}
// If the element is not found, return
if (index == -1) {
return;
}
// Replace the element to be deleted with the last element
heap.set(index, heap.get(heap.size() - 1));
// Remove the last element
heap.remove(heap.size() - 1);
// Heapify the tree starting from the element at the deleted index
while (true) {
int left_child = 2 * index + 1;
int right_child = 2 * index + 2;
int largest = index;
if (left_child < heap.size() && heap.get(left_child) > heap.get(largest)) {
largest = left_child;
}
if (right_child < heap.size() && heap.get(right_child) > heap.get(largest)) {
largest = right_child;
}
if (largest != index) {
int temp = heap.get(index);
heap.set(index, heap.get(largest));
heap.set(largest, temp);
index = largest;
} else {
break;
}
}
}
public static void main(String[] args) {
ArrayList<Integer> arr = new ArrayList<>();
int[] values = { 13, 16, 31, 41, 51, 100 };
for (int i = 0; i < values.length; i++) {
insert(arr, values[i]);
}
System.out.print("Initial heap: ");
for (int j = 0; j < arr.size(); j++) {
System.out.print(arr.get(j) + " ");
}
System.out.println();
deleteMax(arr, 13);
System.out.print("Heap after deleting 13: ");
for (int j = 0; j < arr.size(); j++) {
System.out.print(arr.get(j) + " ");
}
System.out.println();
}
}
Python
# Function to insert an element into the max-heap
def insert(heap, value):
# Add the new element to the end of the heap
heap.append(value)
# Get the index of the last element
index = len(heap) - 1
# Compare the new element with its parent and swap if necessary
while index > 0 and heap[(index - 1) // 2] < heap[index]:
heap[index], heap[(index - 1) // 2] = heap[(index - 1) // 2], heap[index]
# Move up the tree to the parent of the current element
index = (index - 1) // 2
# Function to delete a node from the max-heap
def deleteMax(heap, value):
# Find the index of the element to be deleted
index = -1
for i in range(len(heap)):
if heap[i] == value:
index = i
break
# If the element is not found, return
if index == -1:
return
# Replace the element to be deleted with the last element
heap[index] = heap[-1]
# Remove the last element
heap.pop()
# Heapify the tree starting from the element at the deleted index
while True:
left_child = 2 * index + 1
right_child = 2 * index + 2
largest = index
if left_child < len(heap) and heap[left_child] > heap[largest]:
largest = left_child
if right_child < len(heap) and heap[right_child] > heap[largest]:
largest = right_child
if largest != index:
heap[index], heap[largest] = heap[largest], heap[index]
index = largest
else:
break
# Driver code
if __name__ == "__main__":
arr = []
values = [13, 16, 31, 41, 51, 100]
for value in values:
insert(arr, value)
print("Initial heap:", end=" ")
for val in arr:
print(val, end=" ")
print()
deleteMax(arr, 13)
print("Heap after deleting 13:", end=" ")
for val in arr:
print(val, end=" ")
print()
C#
using System;
using System.Collections.Generic;
class GFG
{
// Function to insert an element into the max-heap
static void insert(List<int> heap, int value)
{
// Add the new element to the end of the heap
heap.Add(value);
// Get the index of the last element
int index = heap.Count - 1;
// Compare the new element with its parent and swap if necessary
while (index > 0 && heap[(index - 1) / 2] < heap[index])
{
int temp = heap[index];
heap[index] = heap[(index - 1) / 2];
heap[(index - 1) / 2] = temp;
// Move up the tree to the parent of the current element
index = (index - 1) / 2;
}
}
// Function to delete a node from the max-heap
static void deleteMax(List<int> heap, int value)
{
// Find the index of the element to be deleted
int index = -1;
for (int i = 0; i < heap.Count; i++)
{
if (heap[i] == value)
{
index = i;
break;
}
}
// If the element is not found, return
if (index == -1)
return;
// Replace the element to be deleted with the last element
heap[index] = heap[heap.Count - 1];
// Remove the last element
heap.RemoveAt(heap.Count - 1);
// Heapify the tree starting from the element at the deleted index
while (true)
{
int left_child = 2 * index + 1;
int right_child = 2 * index + 2;
int largest = index;
if (left_child < heap.Count && heap[left_child] > heap[largest])
largest = left_child;
if (right_child < heap.Count && heap[right_child] > heap[largest])
largest = right_child;
if (largest != index)
{
int temp = heap[index];
heap[index] = heap[largest];
heap[largest] = temp;
index = largest;
}
else
break;
}
}
static void Main()
{
List<int> arr = new List<int>();
int[] values = { 13, 16, 31, 41, 51, 100 };
for (int i = 0; i < values.Length; i++)
{
insert(arr, values[i]);
}
Console.Write("Initial heap: ");
for (int j = 0; j < arr.Count; j++)
{
Console.Write(arr[j] + " ");
}
Console.WriteLine();
deleteMax(arr, 13);
Console.Write("Heap after deleting 13: ");
for (int j = 0; j < arr.Count; j++)
{
Console.Write(arr[j] + " ");
}
Console.WriteLine();
}
}
JavaScript
// Function to insert an element into the max-heap
function insert(heap, value) {
// Add the new element to the end of the heap
heap.push(value);
// Get the index of the last element
let index = heap.length - 1;
// Compare the new element with its parent and swap if necessary
while (index > 0 && heap[Math.floor((index - 1) / 2)] < heap[index]) { // max-heap
let temp = heap[index];
heap[index] = heap[Math.floor((index - 1) / 2)];
heap[Math.floor((index - 1) / 2)] = temp;
// Move up the tree to the parent of the current element
index = Math.floor((index - 1) / 2);
}
}
// Function to delete a node from the max-heap
function deleteMax(heap, value) {
// Find the index of the element to be deleted
let index = -1;
for (let i = 0; i < heap.length; i++) {
if (heap[i] === value) {
index = i;
break;
}
}
// If the element is not found, return
if (index === -1) return;
// Replace the element to be deleted with the last element
heap[index] = heap[heap.length - 1];
// Remove the last element
heap.pop();
// Heapify the tree starting from the element at the deleted index
while (true) {
let left_child = 2 * index + 1;
let right_child = 2 * index + 2;
let largest = index;
if (left_child < heap.length && heap[left_child] > heap[largest]) {
largest = left_child;
}
if (right_child < heap.length && heap[right_child] > heap[largest]) {
largest = right_child;
}
if (largest !== index) {
let temp = heap[index];
heap[index] = heap[largest];
heap[largest] = temp;
index = largest;
} else {
break;
}
}
}
// Driver code
let arr = [];
let values = [13, 16, 31, 41, 51, 100];
for (let i = 0; i < values.length; i++) {
insert(arr, values[i]);
}
console.log("Initial heap:", arr.join(" "));
deleteMax(arr, 13);
console.log("Heap after deleting 13:", arr.join(" "));
OutputInitial heap: 100 41 51 13 31 16
Heap after deleting 13: 100 41 51 16 31
Peek operation - O(1) Time and O(n) Space
To access the maximum element (i.e., the root of the heap), the value of the root node is returned.
C++
#include <iostream>
#include <vector>
using namespace std;
// Function to insert an element into max-heap
void insert(vector<int>& heap, int value) {
// Add the new element at the end
heap.push_back(value);
// Heapify-up to maintain max-heap property
int index = heap.size() - 1;
while (index > 0 && heap[(index - 1) / 2] < heap[index]) {
swap(heap[index], heap[(index - 1) / 2]);
index = (index - 1) / 2;
}
}
// Function to get the peak element of max-heap
int top(const vector<int>& heap) {
if (!heap.empty())
// Root element
return heap[0];
return -1;
}
int main() {
vector<int> maxHeap;
// Insert elements into the max-heap
insert(maxHeap, 9);
insert(maxHeap, 8);
insert(maxHeap, 7);
insert(maxHeap, 6);
insert(maxHeap, 5);
insert(maxHeap, 4);
insert(maxHeap, 3);
insert(maxHeap, 2);
insert(maxHeap, 1);
// Get the peak element (largest in max-heap)
int peakElement = top(maxHeap);
cout << "Peak element: " << peakElement << endl;
return 0;
}
Java
import java.util.ArrayList;
public class GFG{
// Function to insert an element into max-heap
static void insert(ArrayList<Integer> heap, int value) {
// Add the new element at the end
heap.add(value);
// Heapify-up to maintain max-heap property
int index = heap.size() - 1;
while (index > 0 && heap.get((index - 1) / 2) < heap.get(index)) {
int temp = heap.get(index);
heap.set(index, heap.get((index - 1) / 2));
heap.set((index - 1) / 2, temp);
index = (index - 1) / 2;
}
}
// Function to get the peak element of max-heap
static int top(ArrayList<Integer> heap) {
if (!heap.isEmpty())
// Root element
return heap.get(0);
return -1;
}
public static void main(String[] args) {
ArrayList<Integer> maxHeap = new ArrayList<>();
// Insert elements into the max-heap
insert(maxHeap, 9);
insert(maxHeap, 8);
insert(maxHeap, 7);
insert(maxHeap, 6);
insert(maxHeap, 5);
insert(maxHeap, 4);
insert(maxHeap, 3);
insert(maxHeap, 2);
insert(maxHeap, 1);
// Get the peak element (largest in max-heap)
int peakElement = top(maxHeap);
System.out.println("Peak element: " + peakElement);
}
}
Python
# Function to insert an element into max-heap
def insert(heap, value):
# Add the new element at the end
heap.append(value)
# Heapify-up to maintain max-heap property
index = len(heap) - 1
while index > 0 and heap[(index - 1) // 2] < heap[index]:
heap[index], heap[(index - 1) // 2] = heap[(index - 1) // 2], heap[index]
index = (index - 1) // 2
# Function to get the peak element of max-heap
def top(heap):
if heap:
# Root element
return heap[0]
return -1
if __name__ == "__main__":
maxHeap = []
# Insert elements into the max-heap
insert(maxHeap, 9)
insert(maxHeap, 8)
insert(maxHeap, 7)
insert(maxHeap, 6)
insert(maxHeap, 5)
insert(maxHeap, 4)
insert(maxHeap, 3)
insert(maxHeap, 2)
insert(maxHeap, 1)
# Get the peak element (largest in max-heap)
peakElement = top(maxHeap)
print("Peak element:", peakElement)
C#
using System;
using System.Collections.Generic;
class GFG {
// Function to insert an element into max-heap
static void insert(List<int> heap, int value) {
// Add the new element at the end
heap.Add(value);
// Heapify-up to maintain max-heap property
int index = heap.Count - 1;
while (index > 0 && heap[(index - 1) / 2] < heap[index]) {
int temp = heap[index];
heap[index] = heap[(index - 1) / 2];
heap[(index - 1) / 2] = temp;
index = (index - 1) / 2;
}
}
// Function to get the peak element of max-heap
static int top(List<int> heap) {
if (heap.Count > 0)
// Root element
return heap[0];
return -1;
}
static void Main() {
List<int> maxHeap = new List<int>();
// Insert elements into the max-heap
insert(maxHeap, 9);
insert(maxHeap, 8);
insert(maxHeap, 7);
insert(maxHeap, 6);
insert(maxHeap, 5);
insert(maxHeap, 4);
insert(maxHeap, 3);
insert(maxHeap, 2);
insert(maxHeap, 1);
// Get the peak element (largest in max-heap)
int peakElement = top(maxHeap);
Console.WriteLine("Peak element: " + peakElement);
}
}
JavaScript
// Function to insert an element into max-heap
function insert(heap, value) {
// Add the new element at the end
heap.push(value);
// Heapify-up to maintain max-heap property
let index = heap.length - 1;
while (index > 0 && heap[Math.floor((index - 1) / 2)] < heap[index]) {
let temp = heap[index];
heap[index] = heap[Math.floor((index - 1) / 2)];
heap[Math.floor((index - 1) / 2)] = temp;
index = Math.floor((index - 1) / 2);
}
}
// Function to get the peak element of max-heap
function top(heap) {
if (heap.length > 0)
// Root element
return heap[0];
return -1;
}
// Driver code
let maxHeap = [];
// Insert elements into the max-heap
insert(maxHeap, 9);
insert(maxHeap, 8);
insert(maxHeap, 7);
insert(maxHeap, 6);
insert(maxHeap, 5);
insert(maxHeap, 4);
insert(maxHeap, 3);
insert(maxHeap, 2);
insert(maxHeap, 1);
// Get the peak element (largest in max-heap)
let peakElement = top(maxHeap);
console.log("Peak element:", peakElement);
Heapify operation - O(n) Time and O(n) Space
Heapify is an operation that places a node in its correct position in a heap so that the subtree rooted at that node satisfies the heap property.
To build a max heap from an unsorted array, we start from the last non-leaf node and move up to the root, calling heapify on each node. For each node, if it is smaller than any of its children, we swap it with the largest child and continue until it is larger than both children. After all nodes are processed, the array becomes a valid max heap.
C++
#include <iostream>
#include <vector>
using namespace std;
void heapify(vector<int> &arr, int i, int n) {
int largest = i;
int l = 2 * i + 1;
int r = 2 * i + 2;
// If left child exists and is larger than root
if (l < n && arr[l] > arr[largest])
largest = l;
// If right child exists and is larger than largest so far
if (r < n && arr[r] > arr[largest])
largest = r;
// If largest is not root,
// swap and continue heapifying
if (largest != i) {
swap(arr[i], arr[largest]);
// Recursively heapify
heapify(arr, largest, n);
}
}
int main() {
vector<int> arr = {10, 5, 15, 2, 20, 30};
cout << "Original array: ";
for (int i = 0; i < arr.size(); i++)
cout << arr[i] << " ";
// Build max-heap: perform heapify from last
// non-leaf node up to root
for (int i = arr.size()/2 - 1; i >= 0; i--)
heapify(arr, i, arr.size());
// Print array after max-heapify
cout << "\nMax-Heap after heapify operation: ";
for (int i = 0; i < arr.size(); i++)
cout << arr[i] << " ";
return 0;
}
Java
import java.util.ArrayList;
public class GFG {
static void heapify(int[] arr, int i, int n) {
int largest = i;
int l = 2 * i + 1;
int r = 2 * i + 2;
// If left child exists and is larger than root
if (l < n && arr[l] > arr[largest])
largest = l;
// If right child exists and is larger than largest so far
if (r < n && arr[r] > arr[largest])
largest = r;
// If largest is not root, swap and continue heapifying
if (largest != i) {
int temp = arr[i];
arr[i] = arr[largest];
arr[largest] = temp;
// Recursively heapify
heapify(arr, largest, n);
}
}
public static void main(String[] args) {
int[] arr = {10, 5, 15, 2, 20, 30};
System.out.print("Original array: ");
for (int i = 0; i < arr.length; i++)
System.out.print(arr[i] + " ");
// Build max-heap:
for (int i = arr.length / 2 - 1; i >= 0; i--)
heapify(arr, i, arr.length);
// Print array after max-heapify
System.out.print("\nMax-Heap after heapify operation: ");
for (int i = 0; i < arr.length; i++)
System.out.print(arr[i] + " ");
}
}
Python
def heapify(arr, i, n):
largest = i
l = 2 * i + 1
r = 2 * i + 2
# If left child exists and is larger than root
if l < n and arr[l] > arr[largest]:
largest = l
# If right child exists and is larger than largest so far
if r < n and arr[r] > arr[largest]:
largest = r
# If largest is not root, swap and continue heapifying
if largest != i:
arr[i], arr[largest] = arr[largest], arr[i]
# Recursively heapify
heapify(arr, largest, n)
if __name__ == "__main__":
arr = [10, 5, 15, 2, 20, 30]
print("Original array:", end=" ")
for i in range(len(arr)):
print(arr[i], end=" ")
# Build max-heap
for i in range(len(arr)//2 - 1, -1, -1):
heapify(arr, i, len(arr))
# Print array after max-heapify
print("\nMax-Heap after heapify operation:", end=" ")
for i in range(len(arr)):
print(arr[i], end=" ")
C#
using System;
class GFG
{
static void heapify(int[] arr, int i, int n)
{
int largest = i;
int l = 2 * i + 1;
int r = 2 * i + 2;
// If left child exists and is larger than root
if (l < n && arr[l] > arr[largest])
largest = l;
// If right child exists and is larger than largest so far
if (r < n && arr[r] > arr[largest])
largest = r;
// If largest is not root, swap and continue heapifying
if (largest != i)
{
int temp = arr[i];
arr[i] = arr[largest];
arr[largest] = temp;
// Recursively heapify
heapify(arr, largest, n);
}
}
static void Main()
{
int[] arr = {10, 5, 15, 2, 20, 30};
Console.Write("Original array: ");
for (int i = 0; i < arr.Length; i++)
Console.Write(arr[i] + " ");
// Build max-heap
for (int i = arr.Length / 2 - 1; i >= 0; i--)
heapify(arr, i, arr.Length);
// Print array after max-heapify
Console.Write("\nMax-Heap after heapify operation: ");
for (int i = 0; i < arr.Length; i++)
Console.Write(arr[i] + " ");
}
}
JavaScript
function heapify(arr, i, n) {
let largest = i;
let l = 2 * i + 1;
let r = 2 * i + 2;
// If left child exists and is larger than root
if (l < n && arr[l] > arr[largest])
largest = l;
// If right child exists and is larger than largest so far
if (r < n && arr[r] > arr[largest])
largest = r;
// If largest is not root, swap and continue heapifying
if (largest !== i) {
[arr[i], arr[largest]] = [arr[largest], arr[i]];
// Recursively heapify
heapify(arr, largest, n);
}
}
//Driver Code
const arr = [10, 5, 15, 2, 20, 30];
process.stdout.write("Original array: ");
for (let i = 0; i < arr.length; i++)
process.stdout.write(arr[i] + " ");
// Build max-heap
for (let i = Math.floor(arr.length / 2) - 1; i >= 0; i--)
heapify(arr, i, arr.length);
// Print array after max-heapify
console.log("\nMax-Heap after heapify operation: " + arr.join(" "));
OutputOriginal array: 10 5 15 2 20 30
Max-Heap after heapify operation: 30 20 15 2 5 10
Max Heap vs Min Heap
Applications of Max-Heap Data Structure
- Heap Sort: Heaps are used in the heap sort algorithm, an efficient sorting method with worst-case time complexity of O(n log n), applied in database indexing and numerical analysis.
- Memory Management: Heaps help allocate and deallocate memory dynamically, managing memory blocks efficiently for programs.
- Graph Algorithms: Heaps are used in algorithms like Dijkstra, Prim, and Kruskal to implement efficient priority queues.
- Job Scheduling: Heaps enable quick access to highest-priority tasks, making them ideal for task scheduling based on priority or deadlines.
Advantages of Max-Heap Data Structure
- Quick access to maximum: Max-heap allows O(1) access to the largest element.
- Efficient insert/delete: Both operations take O(log n), making it suitable for large datasets.
- Priority Queues: Max-heap can implement priority queues for job scheduling, task prioritization, and event-driven simulations.
- Heap Sort: Can be used for heap sort, an efficient O(n log n) sorting algorithm.
- Space Efficient: Can be implemented as an array, using less memory than BSTs or linked lists.
Explore
DSA Fundamentals
Data Structures
Algorithms
Advanced
Interview Preparation
Practice Problem