Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • DSA
  • Interview Problems on Queue
  • Practice Queue
  • MCQs on Queue
  • Queue Tutorial
  • Operations
  • Applications
  • Implementation
  • Stack vs Queue
  • Types of Queue
  • Circular Queue
  • Deque
  • Priority Queue
  • Stack using Queue
  • Advantages & Disadvantages
Open In App
Next Article:
Max Heap in Java
Next article icon

Max Heap in Java

Last Updated : 08 Feb, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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 

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. 

Methods:

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.

Example

Java
// 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))             return;          if (Heap[pos] < Heap[leftChild(pos)]             || Heap[pos] < Heap[rightChild(pos)]) {              if (Heap[leftChild(pos)]                 > Heap[rightChild(pos)]) {                 swap(pos, leftChild(pos));                 maxHeapify(leftChild(pos));             }             else {                 swap(pos, rightChild(pos));                 maxHeapify(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);         }         size++;     }      // 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];         maxHeapify(0);         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         maxHeap.insert(5);         maxHeap.insert(3);         maxHeap.insert(17);         maxHeap.insert(10);         maxHeap.insert(84);         maxHeap.insert(19);         maxHeap.insert(6);         maxHeap.insert(22);         maxHeap.insert(9);          // Calling maxHeap() as defined above         maxHeap.print();          // Print and display the maximum value in heap         System.out.println("The max val is "                            + maxHeap.extractMax());     } } 

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

Example 

Java
// 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>(                 Collections.reverseOrder());          // Adding items to our priority queue         // using add() method         pQueue.add(10);         pQueue.add(30);         pQueue.add(20);         pQueue.add(400);          // 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())             System.out.println(itr.next());          // Removing the top priority element (or head) and         // printing the modified pQueue using poll()         pQueue.poll();         System.out.println("After removing an element "                            + "with poll function:");         Iterator<Integer> itr2 = pQueue.iterator();         while (itr2.hasNext())             System.out.println(itr2.next());          // Removing 30 using remove() method         pQueue.remove(30);         System.out.println("after removing 30 with"                            + " remove function:");          Iterator<Integer> itr3 = pQueue.iterator();         while (itr3.hasNext())             System.out.println(itr3.next());          // 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());     } } 

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

Next Article
Max Heap in Java

A

Amaninder.Singh
Improve
Article Tags :
  • Java
  • Heap
  • DSA
  • priority-queue
  • java-priority-queue
  • Java-Queue-Programs
Practice Tags :
  • Heap
  • Java
  • priority-queue

Similar Reads

    Max Heap in C++
    A max heap is defined as a complete binary tree where every node's value is at least as large as the values of its children. This makes it useful for implementing priority queues, where the highest priority element is always at the root. In this article, we will learn how to implement the max heap d
    8 min read
    BigDecimal max() Method in Java
    The java.math.BigDecimal.max(BigDecimal val) method in Java is used to compare two BigDecimal values and return the maximum of the two. This is opposite to BigDecimal max() method in Java. Syntax: public BigDecimal max(BigDecimal val) Parameters: The function accepts a BigDecimal object val as param
    2 min read
    What is Max Heap?
    Max Heap is a type of binary heap where the key at the root must be the maximum among all keys present in the binary heap. The same property must be recursively true for all nodes in the binary tree. Max Heap Definition:Max Heap is a complete binary tree, where value of each node is greater than or
    3 min read
    Max Heap meaning in DSA
    A max heap is a complete binary tree in which every parent node has a value greater than or equal to its children nodes. Example of Max HeapProperties of a Max Heap :A max heap is a complete binary tree, meaning that all levels of the tree are completely filled, except possibly the last level which
    3 min read
    IntStream max() in Java with examples
    java.util.stream.IntStream in Java 8, deals with primitive ints. It helps to solve the problems like finding maximum value in array, finding minimum value in array, sum of all elements in array, and average of all values in array in a new way. IntStream max() returns an OptionalInt describing the ma
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences