luciopaiva / heapify

The fastest JavaScript priority queue out there. Zero dependencies.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Doesn't support duplicate priorities

lucasmoeskops opened this issue · comments

The priority queue seems to give incorrect values when duplicate priorities are used.

When I try this:

const queue = new Heapify();
queue.push(1, 1);
console.log(queue.pop());
queue.push(2, 2);
console.log(queue.pop());
queue.push(3, 3);
queue.push(4, 5);
console.log(queue.pop());
queue.push(5, 4);
queue.push(6, 5);
console.log(queue.pop());
queue.push(7, 7);
console.log(queue.pop());
queue.push(8, 6);
console.log(queue.pop());

I would expect:
1 2 3 5 4 6 8 7

But I get:
1 2 3 5 4 8 6 7

So key 8 comes before key 6, even though the priority of key 6 is lower.

If this is intended behavior, I propose to add it to the documentation.

Hey @lucasmoeskops,

Thanks for reporting this. It was indeed a bug. It was introduced in 0.4.0 and is now fixed in 0.4.1.

Notice, however, that the bug didn't have anything to do with duplicate priorities. The two keys with the same priority in your example was not the cause of the bug, which can be reproduced by this simpler example where keys have distinct priorities.

Nevertheless, you are right that 1 2 3 5 4 8 6 7 should not be the expected outcome - it's just that it may not be 1 2 3 5 4 6 8 7 either!

The explanation is that Heapify's heap implementation is not stable. In your example, keys 4 and 6 have the same priority. Only in stable implementations we'd expect 4 to be popped before 6, so 1 2 3 5 6 4 8 7 is also a valid sequence in Heapify.

I will add a note about this in the docs.

Here it is.

Thanks for the fix and the explanation!