1

I want to write a program which can sort Items by Priority Queue

But the code below doesn't work and I dont know the problem

any help?? thanks in advance for your attention

public class SortingASequenceByPriorityQueue {

public static void main(String[] args) {  
    PriorityQueue<Integer> pQueue = new PriorityQueue<Integer>(1000, new Comparator<Integer>() {    

            public int compare(Integer w1, Integer w2) {                           
                if(w1.intValue()> w2.intValue())
                    return 1;
                else if( w1.intValue()< w2.intValue())
                    return -1;
                return 0;
            }        
        });    

         pQueue.add(12);    
         pQueue.add(1);     
         pQueue.add(5);    
         pQueue.add(22);    
         pQueue.add(3);    
         pQueue.add(2);    
         pQueue.add(124);    
         pQueue.add(14);    
         pQueue.add(111);    
         pQueue.add(9);    
         pQueue.add(30);    

        Object[] ar = pQueue.toArray();    
        for (int i = 0; i< ar.length; i++){    
            System.out.println(ar[i].toString());    
        }   
}  

}  

The output is this :

1 3 2 14 9 5 124 22 111 12 30

  • 2
    This is specified in the doc. _"Returns an array containing all of the elements in this queue. The elements are in **no particular order**."_ – Alexis C. Jan 04 '14 at 16:38
  • It appears your objective is to sort a collection of integers in ascending order. Why do you need to use a `PriorityQueue` when there are other/better alternatives? – Josh M Jan 04 '14 at 16:41
  • This is where reading the Javadoc would have answered your question. – Peter Lawrey Jan 04 '14 at 17:29

1 Answers1

7

What you are effectively trying to do is heap sort. But you can't do that with toArray() which, for PriorityQueue, states

Returns an array containing all of the elements in this queue. The elements are in no particular order.

What you'll want to do is remove the elements from the PriorityQueue one by one and add them to some array.

Object[] arr = new Object[pQueue.size()];
for (int i = 0; i < arr.length; i++) {
    arr[i] = pQueue.remove();
}

System.out.println(Arrays.toString(arr));

which prints

[1, 2, 3, 5, 9, 12, 14, 22, 30, 111, 124]

This works because the PriorityQueue re-arranges itself when you add or remove an element to maintain the heap property.

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724