0
votes

I want to sort the elements using Priority Queue in Java.

Here is my code. What is wrong in it?

import java.io.*;
import java.util.*;

class PQ {
    static class IntCompare implements Comparator<Integer>{
        @Override
        public int compare(Integer arg0, Integer arg1) {
            if(arg0 > arg1)
                return -1;
            else if(arg0 < arg1)
                return 1;
            else
                return 0;
        }
   }

    public static void main (String[] args) {
        int a[] = { 1, 3, 8, 5, 2, 6 };

        Comparator<Integer> c = new IntCompare();
        PriorityQueue<Integer> pq=new PriorityQueue<>(c);

        for(int i = 0; i < a.length; i++)
            pq.add(a[i]);

        System.out.println(pq);
    }
}

my output is:

8, 5, 6, 1, 2, 3

correct output:

8, 6, 5, 3, 2, 1
3
Your PriorityQueue is ordered, the toString just outputs them in no particular order (as clearly stated in the Javadoc). Also consider using Comparator.reverseOrder() over reinventing the wheel. - Ben

3 Answers

1
votes

When you call System.out.println(pq), the toString method is called implicitly.

The toString method of PriorityQueue extends from AbstractCollection, which

Returns a string representation of this collection. The string representation consists of a list of the collection's elements in the order they are returned by its iterator, enclosed in square brackets ("[]").

While the iterator of PriorityQueue is not guaranteed to traverse in particular order:

The Iterator provided in method iterator() is not guaranteed to traverse the elements of the priority queue in any particular order.

since the queue is based on heap.

You can poll elements one by one to get ordered elements:

while (pq.size() != 0) {
    System.out.print(pq.poll() + ","); // 8,6,5,3,2,1,
}
0
votes

You should poll() all the elements until the queue is empty and save them somewhere to get them ordered.

0
votes

Try the following, list contains items in sorted order. The priority key by itself not maintain the elements in sorted order, it just keeps the top element as minimum or maximum based on your implementation of the PQ.

public static void main (String[] args) {
        int a[]={1,3,8,5,2,6};
        Comparator<Integer> c = new IntCompare();
        PriorityQueue<Integer> pq=new PriorityQueue<>(c);
        for(int i=0;i<a.length;i++)
            pq.add(a[i]);
        ArrayList<Integer> list  = new ArrayList<>();
        while(!pq.isEmpty()){
            list.add(pq.poll());
        }
        for(Integer i : list)
            System.out.println(i);
}