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
toStringjust outputs them in no particular order (as clearly stated in the Javadoc). Also consider usingComparator.reverseOrder()over reinventing the wheel. - Ben