priority queue - Retrieve item from the middle of a PriorityQueue in Java -
given following code:
import java.util.*; class simpletest { public static void main(string[] args) { priorityqueue<integer> pq = new priorityqueue<>(); pq.add(1); pq.add(2); pq.add(3); pq.add(4); pq.add(5); pq.add(6); pq.add(7); int index = 0; int middlenumber = 0; iterator = pq.iterator(); //is number odd if(pq.size() % 2 != 0) { system.out.println(pq.size()); //keep removing queue until reached queuesize/2 (rounded up) while(it.hasnext() && index++ <= ((pq.size() >> 1) + 1)) { middlenumber = pq.poll(); } system.out.println("the middle number is: " + (float)middlenumber); } } } this works on odd numbers, not others, , fail see why.
given queue of 7 items, code above returns 4 in middle of queue.
but if try queue 9 elements (1-9). returns 4, when should 5.
why happen?
the main problem line:
middlenumber = pq.poll(); decrements size of queue, affects meaning of line:
while(it.hasnext() && index++ <= ((pq.size() >> 1) + 1)) { then there secondary problems — while expression wrong written — think because tried tweak while work case queue started 7 elements, not understanding underlying bug.
instead, should precompute index want, , poll point:
int indexofmiddlenumber = pq.size() / 2; (int index = 0; index < indexofmiddlenumber; ++index) { pq.poll(); } int middlenumber = pq.poll(); (note there's no use iterator, , it's bad idea call it.hasnext() in loop that's modifying underlying collection. i'm surprised priorityqueue isn't giving concurrentmodificationexception this.)
Comments
Post a Comment