Search code examples
javaqueuecomparatorpriority-queuecomparable

sort the elements in java using priority queue


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

Solution

  • 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,
    }