Max Heap in Java

JavaObject Oriented ProgrammingProgramming

Max heap is a complete binary tree, wherein the value of a root node at every step is greater than or equal to value at the child node.

Below is an implementation of Max Heap using library functions.

Example

 Live Demo

import java.util.*;
public class Demo{
   public static void main(String args[]){
      PriorityQueue<Integer> my_p_queue = new PriorityQueue<Integer>(Collections.reverseOrder());
      my_p_queue.add(43);
      my_p_queue.add(56);
      my_p_queue.add(99);
      System.out.println("The elements in the priority queue are : ");
      Iterator my_iter = my_p_queue.iterator();
      while (my_iter.hasNext())
      System.out.println(my_iter.next());
      my_p_queue.poll();
      System.out.println("After removing an element using the poll function, the queue elements are :");
      Iterator<Integer> my_iter_2 = my_p_queue.iterator();
      while (my_iter_2.hasNext())
      System.out.println(my_iter_2.next());
      Object[] my_arr = my_p_queue.toArray();
      System.out.println("The array representation of max heap : ");
      for (int i = 0; i < my_arr.length; i++)
      System.out.println("Value: " + my_arr[i].toString());
   }
}

Output

The elements in the priority queue are :
99
43
56
After removing an element using the poll function, the queue elements are :
56
43
The array representation of max heap :
Value: 56
Value: 43

A class named Demo contains the main function. Inside the main function, an instance of priority queue is defined and elements are added into it using the ‘add’ function. An iterator is defined and it

is used to iterate over the elements in the priority queue. The ‘poll’ function is used to remove an element from the list. Next, the elements are iterated over and displayed on the screen.

raja
Published on 07-Jul-2020 11:46:47
Advertisements