Max Heap in Java
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 a index k, then its left child is stored at index 2k+1 and its right child at index 2k+2.
Example of 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:
1) getMax(): It returns the root element of Max Heap. Time Complexity of this operation is O(1).
2) extractMax(): Removes the maximum element from MaxHeap. Time Complexity of this Operation is O(Log n) as this operation needs to maintain the heap property (by calling heapify()) after removing root.
4) insert(): Inserting a new key takes O(Log n) time. We add a new key at the end of the tree. If 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 below implementation, we do indexing from index 1 to simplify the implementation.
// Java program to implement Max Heap 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.maxsize = maxsize; this.size = 0; Heap = new int[this.maxsize + 1]; Heap[0] = Integer.MAX_VALUE; } // Returns position of parent private int parent(int pos) { return pos / 2; } // Below two functions return left and // right children. private int leftChild(int pos) { return (2 * pos); } private int rightChild(int pos) { return (2 * pos) + 1; } // Returns true of given node is leaf private boolean isLeaf(int pos) { if (pos >= (size / 2) && pos <= size) { return true; } return false; } private void swap(int fpos, int spos) { int tmp; tmp = Heap[fpos]; Heap[fpos] = Heap[spos]; Heap[spos] = tmp; } // A recursive function to max heapify the given // subtree. This function assumes that the left and // right subtrees are already heapified, we only need // to fix the root. 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)); } } } // 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); } } public void print() { for (int i = 1; i <= size / 2; i++) { System.out.print(" PARENT : " + Heap[i] + " LEFT CHILD : " + Heap[2 * i] + " RIGHT CHILD :" + Heap[2 * i + 1]); System.out.println(); } } // Remove an element from max heap public int extractMax() { int popped = Heap[1]; Heap[1] = Heap[size--]; maxHeapify(1); return popped; } public static void main(String[] arg) { System.out.println("The Max Heap is "); MaxHeap maxHeap = new MaxHeap(15); 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); maxHeap.print(); System.out.println("The max val is " + maxHeap.extractMax()); } } |
The Max Heap is PARENT : 84 LEFT CHILD : 22 RIGHT CHILD :19 PARENT : 22 LEFT CHILD : 17 RIGHT CHILD :10 PARENT : 19 LEFT CHILD : 5 RIGHT CHILD :6 PARENT : 17 LEFT CHILD : 3 RIGHT CHILD :9 The max val is 84
Using 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()
// Java program to demonstrate working of PriorityQueue // as a Max Heap import java.util.*; class Example { public static void main(String args[]) { // Creating empty priority queue PriorityQueue<Integer> pQueue = new PriorityQueue<Integer>(Collections.reverseOrder()); // Adding items to the pQueue using add() 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 Java using remove() pQueue.remove(30); System.out.println("after removing Java 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()); } } |
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 Java with remove function: 20 10 Priority queue contains 20 or not?: true Value in array: Value: 20 Value: 10
Recommended Posts:
- Heap Sort for decreasing order using min heap
- Min Heap in Java
- Java Program for Heap Sort
- Convert min Heap to max Heap
- K-ary Heap
- K’th Least Element in a Min-Heap
- Binary Heap
- Binomial Heap
- Convert BST to Min Heap
- Convert BST to Max Heap
- Skew Heap
- Print all nodes less than a value x in a Min Heap.
- Implementation of Binomial Heap
- Where is Heap Sort used practically?
- Minimum element in a max heap
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



