I am creating a priority queue and using comparator to make sure things are storing in descending order, but end of the day it does not store the values in descending order.
int[][] a = {{1,2},{6,5},{3,4}};
PriorityQueue<int[]> pq = new PriorityQueue<>(new Comparator<int[]>() {
@Override
public int compare(int[] o1, int[] o2) {
int s1 = (int) (Math.pow(o1[0], 2) Math.pow(o1[1],2));
int s2 = (int) (Math.pow(o2[0], 2) Math.pow(o2[1],2));
return Integer.compare(s2, s1);
//Also tried Integer.compare(s1, s2); it returns in ascending order
}
});
When I am adding the values to priorityQueue, I expect this to be added as {6,5}, {3,4}, {1,2}. But it is adding as {6,5}, {1,2}, {3,4}.
for(int i=0; i<a.length;i ) {
pq.add(a[i]);
}
What is the mistake am doing above?
CodePudding user response:
Try to traverse queue:
while (!pq.isEmpty()) {
System.out.println(Arrays.toString(pq.poll()));
}
[6, 5]
[3, 4]
[1, 2]