0

My understanding is that the natural ordering for a priority queue is least to greatest. So it's expected that the least negative numbers come first before positive numbers.

PriorityQueue<Integer> q = new PriorityQueue<>();
q.add(-5);
q.add(10);
q.add(-5);

This yields a result [-5, 10, -5] which is not what I expect. Should be [-5, -5, 10]. However if I add a third -5, it then sorts it correctly [-5, -5, -5, 10]

If we want to be reversed (greatest positive numbers to least negative numbers):

PriorityQueue q = new PriorityQueue<>((a,b) -> Integer.compare(b,a))
q.add(-5);
q.add(10);
q.add(-3);

This yields a result [10, -5, -3] but it should be [10, -3, -5].

Can anyone explain this occurrence to me? And if there is a comparator that can actually correctly do what I want it to do? Do I have to write a customized approach to dealing with negative numbers?

ohasumi
  • 1
  • 1

0 Answers0