// return the k 'smallest' elements of the queue
// runs in O(k log k) time
// this is the equivalent of repeatedly calling poll, but
// it has a better computational complexity, which can be
// important for large data sets.
But it's not equivalent, because poll() removes the polled element and this function not. Example:
const FastPriorityQueue = require('fastpriorityqueue')
const q = new FastPriorityQueue()
q.add(1)
q.add(2)
q.add(3)
console.log(q.size)
// >> Outputs 3
q.kSmallest(2)
console.log(q.size)
// >> Outputs 3
for (let i = 0; i < 2; i++) {
q.poll()
}
console.log(q.size)
// >> Outputs 1
Is this behavior expected? Either the comment or the documentation should be changed.
Yes, the explanation in the documentation was incorrect. The elements are not removed from the priority queue (by design). I have updated the documentation.
The
kSmallest
function has a comment saying:But it's not equivalent, because
poll()
removes the polled element and this function not. Example:Is this behavior expected? Either the comment or the documentation should be changed.