📢 Too many exams? Don’t know which one suits you best? Book Your Free Expert 👉 call Now!


    Question

    Consider the following Java code snippet:    

    import java.util.ArrayList;     import java.util.Arrays;     import java.util.List;     import java.util.PriorityQueue;     public class HeapQuestion10 {         public static void main(String[] args) {             List numbers = Arrays.asList(7, 2, 9, 1, 5);             PriorityQueue pq = new PriorityQueue(numbers); // Initialize with a collection             System.out.println(pq.poll());             System.out.println(pq.poll());             System.out.println(pq.poll());         }     }     What will be the output of this program?
    A 7, 2, 9 Correct Answer Incorrect Answer
    B 1, 2, 5 Correct Answer Incorrect Answer
    C 1, 2, 7 Correct Answer Incorrect Answer
    D 2, 1, 5 Correct Answer Incorrect Answer
    E 9, 7, 5 Correct Answer Incorrect Answer

    Solution

    When a PriorityQueue is initialized with a Collection (like numbers list here), it performs a "heapify" operation. This operation builds a min-heap (by default) from the given elements. The time complexity for building a heap from N elements is O(N).     1.  List numbers = Arrays.asList(7, 2, 9, 1, 5);     2.  PriorityQueue pq = new PriorityQueue<>(numbers);         The PriorityQueue is constructed and heapified. The elements will be arranged such that the smallest element is at the root. The conceptual order of elements in the min-heap will be {1, 2, 5, 7, 9}.     3.  System.out.println(pq.poll());         Removes and prints the smallest element: 1. Heap: {2, 5, 7, 9}.     4.  System.out.println(pq.poll());         Removes and prints the next smallest element: 2. Heap: {5, 7, 9}.     5.  System.out.println(pq.poll());         Removes and prints the next smallest element: 5. Heap: {7, 9}.     Therefore, the output is 1, 2, 5.

    Practice Next
    More IT Operating System Questions
    ask-question