lemire / FastPriorityQueue.js

a fast heap-based priority queue in JavaScript
Apache License 2.0
357 stars 57 forks source link

kSmallest() not equivalent to calling poll() repeatedly #26

Closed alesanmed closed 3 years ago

alesanmed commented 3 years ago

The kSmallest function has a comment saying:

// 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.

lemire commented 3 years ago

Yes, the explanation in the documentation was incorrect. The elements are not removed from the priority queue (by design). I have updated the documentation.