I tried to implement the priority Queue with inner Comparator class with decreasing order, but when i printed the priority queue I am not getting the correct result. When I tried the same comparator code for Collection.sort to implement the sorting for list (with same values). I am getting the correct result. Could you please explain?
//int[] nums = {50,10, 20, 30, 40};
public static void TestComparatorcomparemethod(int[] nums){
PriorityQueue<Integer> pq= new PriorityQueue<>(nums.length,new Comparator<Integer>(){
@Override
public int compare(Integer o1,Integer o2){
int a = (int)o1;
int b = (int)o2;
if (a > b)
return -1;
else if (a==b)
return 0;
else
return 1;
}
});
for (int node:nums){
pq.add(node);}
System.out.println("pq values are " + pq);
}
The answer for the above code is pq values are [50, 40, 20, 10, 30]
List<Integer> al = new ArrayList<>();
al.add(50);
al.add(10);
al.add(20);
al.add(30);
al.add(40);
Collections.sort(al, new Comparator<Integer>(){
@Override
public int compare(Integer o1,Integer o2){
int a = (int)o1;
int b = (int)o2;
if (a > b)
return -1;
else if (a==b)
return 0;
else
return 1;
}
} );
System.out.println("The arraylist values are: " + al);
The answer for the above code is The array values are: [50, 40, 30, 20, 10]