Search code examples
javacomparatorpriority-queue

PriorityQueue with inner comparator class


I tried to implement the priority Queue with inner Comparator class with decreasing order, but when i printed the priority queue I am not getting the correct result. When I tried the same comparator code for Collection.sort to implement the sorting for list (with same values). I am getting the correct result. Could you please explain?

//int[] nums = {50,10, 20, 30, 40};
    public static void TestComparatorcomparemethod(int[] nums){
        PriorityQueue<Integer> pq= new PriorityQueue<>(nums.length,new Comparator<Integer>(){
            @Override
            public int compare(Integer o1,Integer o2){
                int a = (int)o1;
                int b = (int)o2;
                if (a > b)
                    return -1;
                else if (a==b)
                    return 0;
                else
                    return 1;
            }
        });
        for (int node:nums){
            pq.add(node);}
        System.out.println("pq values are " + pq);
}

The answer for the above code is pq values are [50, 40, 20, 10, 30]

        List<Integer> al = new ArrayList<>();
        al.add(50);
        al.add(10);
        al.add(20);
        al.add(30);
        al.add(40);
        Collections.sort(al, new Comparator<Integer>(){
            @Override
            public int compare(Integer o1,Integer o2){
                int a = (int)o1;
                int b = (int)o2;
                if (a > b)
                    return -1;
                else if (a==b)
                    return 0;
                else
                    return 1;
            }
        } );
        System.out.println("The arraylist values are: " + al);

The answer for the above code is The array values are: [50, 40, 30, 20, 10]


Solution

  • When you print the priority queue element with:

    System.out.println("The arraylist values are: " + al);
    

    The order of elements that will be printed is not guaranteed to be sorted. This may happens because a priority queue is implemented using some kind of heap data structure for efficient min element lookup and insertions. So when you print the elements with the above code you print the elements in the heap which are not sorted.

    This does not mean that your priority queue is not working.

    The right way-most efficient to traverse elements in a priority queue is with poll() function, for example:

    pq_elem = pq.poll()
    while(pq_elem != Null){
      System.out.println(pq_elem)
      pq_elem.poll()
    }