Search code examples
javapriority-queueternary-operator

PriorityQueue and ternary operator


In method_one:

  1. PriorityQueue<Integer> bigger = lower.size() > higher.size() ? lower : higher;
  2. PriorityQueue<Integer> smaller = lower.size() > higher.size() ? higher : lower;

In method_two:

  1. PriorityQueue<Integer> bigger = lower.size() > higher.size() ? lower : higher;
  2. PriorityQueue<Integer> smaller = lower.size() < higher.size() ? lower : higher;

Here lower is Max_heap priority queue, and higher is Min_heap priority queue.

Line 2 and 4 are same, but getting wrong answers. And getting right answer when using line 2 at line 4. Why this strange behaviour, even they are same?


Solution

  • in line 2:

    if lower.size() == higher.size() then choose lower

    in line 4:

    if lower.size() == higher.size() then chose higher

    thats the difference. You get different answer if you something do wrong when work with higher priority queue or lower priority queue.

    From @Andreas comment in question this line added:

    The inverse of > is <=, not <