It returned true as there exists the number in a heap. Finally, we checked if the heap contains a number 2 using the contains() method. It printed the values 1 and 2 as we already removed 3 and 4. Then, we used the remove() method to remove the number 3, and we printed the remaining elements in a heap. Then, the poll() method removed the maximum number, 4. The peek() method returned the value 4, which is the largest in a heap. We added the values 1, 2, 3, and 4 to the heap. In the example below, the import java.util.* will import the PriorityQueue class, which we used to create a max-heap. Finally, use the contains() method with a parameter 20. Next, call the remove() method with a value 30 as the parameter and then print the elements in the array using the iterator() and hasNext() methods. Then, use the poll() method on the object. Call the peek() method with the object pq and print it. Use the add() method to add four integer values. Write Collections.reverseOrder() in the parenthesis while creating the object. Use the generic type to create the Integer instance. Then create an instance of the PriorityQueue class as pq. Create a class MaxHeap and write the main method. We can use the contains() method to check if an element exists in a heap.įor example, import everything from the java.util package. The poll() method returns and removes the value at the root node. We can use the peek() method to display the element from the root node in a heap. The class implements the min-heap by default, and we can use the reverseOrder() method from Collections to implement the max-heap. We can use the PriorityQueue class to implement the heaps in Java. Implement Max-Heap With the PriorityQueue Class and Collections.reverseOrder() in Java The odd levels like 1, 3, 5 represent the maximum values. The minimum values are represented with even levels like 0, 2, 4. The root node contains the smallest value, and the next level below it represents the largest value. The complexity to remove or insert the elements to and from the heap is O(log N).Ī min-max heap is a data structure that contains alternating minimum and maximum levels. We can get the largest and the smallest element in O(1). Therefore, the heap data structure makes it easier to extract the largest and the smallest element from an array. Similarly, the max-heap has the largest value in the root node or the parent node. The minimum heap, also known as the min-heap, has the smallest value in its root node or the parent node. There are two types of heaps, and they are minimum heap and maximum heap. Introduction to Min-Max Heap in JavaĪ heap is a data structure based upon trees, and it forms a complete binary tree. We will also demonstrate the insertion and deletion of the elements from the heap. This article will implement a max-heap and a min-heap using the PriorityQueue class.
0 Comments
Leave a Reply.AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |