Introduction to MaxHeap (original) (raw)

A **Max-Heap is a Data Structure with the following properties:

Implementation of Max-Heap Data Structure

A heap can be efficiently represented using an array.
If a node is stored at index i:

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:

**Illustration:

Insertion-In-Max-Heap

C++ `

#include #include using namespace std;

void insert(vector& 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 arr; vectorvalues = { 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 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 <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mrow><mi>v</mi><mi>a</mi><mi>l</mi><mi>u</mi><mi>e</mi></mrow><mi>i</mi><mi>n</mi><mi>t</mi><mi>o</mi><mi>t</mi><mi>h</mi><mi>e</mi><mi>m</mi><mi>a</mi><mi>x</mi><mo>−</mo><mi>h</mi><mi>e</mi><mi>a</mi><mi>p</mi><mo>:</mo></mrow><annotation encoding="application/x-tex">{value} into the max-heap: </annotation></semantics></math></span><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.7778em;vertical-align:-0.0833em;"></span><span class="mord"><span class="mord mathnormal" style="margin-right:0.03588em;">v</span><span class="mord mathnormal">a</span><span class="mord mathnormal" style="margin-right:0.01968em;">l</span><span class="mord mathnormal">u</span><span class="mord mathnormal">e</span></span><span class="mord mathnormal">in</span><span class="mord mathnormal">t</span><span class="mord mathnormal">o</span><span class="mord mathnormal">t</span><span class="mord mathnormal">h</span><span class="mord mathnormal">e</span><span class="mord mathnormal">ma</span><span class="mord mathnormal">x</span><span class="mspace" style="margin-right:0.2222em;"></span><span class="mbin">−</span><span class="mspace" style="margin-right:0.2222em;"></span></span><span class="base"><span class="strut" style="height:0.8889em;vertical-align:-0.1944em;"></span><span class="mord mathnormal">h</span><span class="mord mathnormal">e</span><span class="mord mathnormal">a</span><span class="mord mathnormal">p</span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">:</span></span></span></span>{arr.join(' ')}); }

``

Output

Inserted 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:

**Illustration:

C++ `

#include #include using namespace std;

void insert(vector& 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& 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 arr; vectorvalues = { 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 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(" "));

`

Output

Initial 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.

peak-element-of-max-heap

C++ `

#include #include using namespace std;

// Function to insert an element into max-heap void insert(vector& 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& heap) { if (!heap.empty())

// Root element
    return heap[0]; 
return -1; 

}

int main() { vector 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.

heapify-operations-in-max-heap

C++ `

#include #include using namespace std;

void heapify(vector &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 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(" "));

`

Output

Original array: 10 5 15 2 20 30 Max-Heap after heapify operation: 30 20 15 2 5 10

Max Heap vs Min Heap

420046868

for more detail refer - Difference between Min Heap and Max Heap

Applications of Max-Heap Data Structure

Advantages of Max-Heap Data Structure