Open In App
Related Articles

Max Heap in Java

Like Article
Save Article
Report issue

A max-heap is a complete binary tree in which the value in each internal node is greater than or equal to the values in the children of that node. Mapping the elements of a heap into an array is trivial: if a node is stored an index k, then its left child is stored at index 2k + 1 and its right child at index 2k + 2.

Illustration: Max Heap 


How is Max Heap represented? 

A-Max Heap is a Complete Binary Tree. A-Max heap is typically represented as an array. The root element will be at Arr[0]. Below table shows indexes of other nodes for the ith node, i.e., Arr[i]: 

Arr[(i-1)/2] Returns the parent node. 
Arr[(2*i)+1] Returns the left child node. 
Arr[(2*i)+2] Returns the right child node.

Operations on Max Heap are as follows:

  • getMax(): It returns the root element of Max Heap. The Time Complexity of this operation is O(1).
  • extractMax(): Removes the maximum element from MaxHeap. The Time Complexity of this Operation is O(Log n) as this operation needs to maintain the heap property by calling the heapify() method after removing the root.
  •  insert(): Inserting a new key takes O(Log n) time. We add a new key at the end of the tree. If the new key is smaller than its parent, then we don’t need to do anything. Otherwise, we need to traverse up to fix the violated heap property.

Note: In the below implementation, we do indexing from index 1 to simplify the implementation. 


There are 2 methods by which we can achieve the goal as listed: 

  1. Basic approach by creating maxHeapify() method
  2. Using Collections.reverseOrder() method via library Functions

Method 1: Basic approach by creating maxHeapify() method

We will be creating a method assuming that the left and right subtrees are already heapified, we only need to fix the root.



// Java program to implement Max Heap
// Main class
public class MaxHeap {
    private int[] Heap;
    private int size;
    private int maxsize;
    // Constructor to initialize an
    // empty max heap with given maximum
    // capacity
    public MaxHeap(int maxsize)
        // This keyword refers to current instance itself
        this.maxsize = maxsize;
        this.size = 0;
        Heap = new int[this.maxsize];
    // Method 1
    // Returning position of parent
    private int parent(int pos) { return (pos - 1) / 2; }
    // Method 2
    // Returning left children
    private int leftChild(int pos) { return (2 * pos) + 1; }
    // Method 3
    // Returning right children
    private int rightChild(int pos)
        return (2 * pos) + 2;
    // Method 4
    // Returning true if given node is leaf
    private boolean isLeaf(int pos)
        if (pos > (size / 2) && pos <= size) {
            return true;
        return false;
    // Method 5
    // Swapping nodes
    private void swap(int fpos, int spos)
        int tmp;
        tmp = Heap[fpos];
        Heap[fpos] = Heap[spos];
        Heap[spos] = tmp;
    // Method 6
    // Recursive function to max heapify given subtree
    private void maxHeapify(int pos)
        if (isLeaf(pos))
        if (Heap[pos] < Heap[leftChild(pos)]
            || Heap[pos] < Heap[rightChild(pos)]) {
            if (Heap[leftChild(pos)]
                > Heap[rightChild(pos)]) {
                swap(pos, leftChild(pos));
            else {
                swap(pos, rightChild(pos));
    // Method 7
    // Inserts a new element to max heap
    public void insert(int element)
        Heap[size] = element;
        // Traverse up and fix violated property
        int current = size;
        while (Heap[current] > Heap[parent(current)]) {
            swap(current, parent(current));
            current = parent(current);
    // Method 8
    // To display heap
    public void print()
        for (int i = 0; i < size / 2; i++) {
            System.out.print("Parent Node : " + Heap[i]);
            if (leftChild(i)
                < size) // if the child is out of the bound
                        // of the array
                System.out.print(" Left Child Node: "
                                 + Heap[leftChild(i)]);
            if (rightChild(i)
                < size) // the right child index must not
                        // be out of the index of the array
                System.out.print(" Right Child Node: "
                                 + Heap[rightChild(i)]);
            System.out.println(); // for new line
    // Method 9
    // Remove an element from max heap
    public int extractMax()
        int popped = Heap[0];
        Heap[0] = Heap[--size];
        return popped;
    // Method 10
    // main driver method
    public static void main(String[] arg)
        // Display message for better readability
        System.out.println("The Max Heap is ");
        MaxHeap maxHeap = new MaxHeap(15);
        // Inserting nodes
        // Custom inputs
        // Calling maxHeap() as defined above
        // Print and display the maximum value in heap
        System.out.println("The max val is "
                           + maxHeap.extractMax());


The Max Heap is 
Parent Node : 84 Left Child Node: 22 Right Child Node: 19
Parent Node : 22 Left Child Node: 17 Right Child Node: 10
Parent Node : 19 Left Child Node: 5 Right Child Node: 6
Parent Node : 17 Left Child Node: 3 Right Child Node: 9
The max val is 84

Method 2: Using Collections.reverseOrder() method via library Functions 

We use PriorityQueue class to implement Heaps in Java. By default Min Heap is implemented by this class. To implement Max Heap, we use Collections.reverseOrder() method. 



// Java program to demonstrate working
// of PriorityQueue as a Max Heap
// Using Collections.reverseOrder() method
// Importing all utility classes
import java.util.*;
// Main class
class GFG {
    // Main driver method
    public static void main(String args[])
        // Creating empty priority queue
        PriorityQueue<Integer> pQueue
            = new PriorityQueue<Integer>(
        // Adding items to our priority queue
        // using add() method
        // Printing the most priority element
        System.out.println("Head value using peek function:"
                           + pQueue.peek());
        // Printing all elements
        System.out.println("The queue elements:");
        Iterator itr = pQueue.iterator();
        while (itr.hasNext())
        // Removing the top priority element (or head) and
        // printing the modified pQueue using poll()
        System.out.println("After removing an element "
                           + "with poll function:");
        Iterator<Integer> itr2 = pQueue.iterator();
        while (itr2.hasNext())
        // Removing 30 using remove() method
        System.out.println("after removing 30 with"
                           + " remove function:");
        Iterator<Integer> itr3 = pQueue.iterator();
        while (itr3.hasNext())
        // Check if an element is present using contains()
        boolean b = pQueue.contains(20);
        System.out.println("Priority queue contains 20 "
                           + "or not?: " + b);
        // Getting objects from the queue using toArray()
        // in an array and print the array
        Object[] arr = pQueue.toArray();
        System.out.println("Value in array: ");
        for (int i = 0; i < arr.length; i++)
            System.out.println("Value: "
                               + arr[i].toString());


Head value using peek function:400
The queue elements:
After removing an element with poll function:
after removing 30 with remove function:
Priority queue contains 20 or not?: true
Value in array: 
Value: 20
Value: 10

Last Updated : 08 Feb, 2023
Like Article
Save Article
Share your thoughts in the comments
Similar Reads