Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Bug] PriorityQueue: Inserting previously extracted element does not work #139

Open
erikw opened this issue Dec 12, 2022 · 1 comment
Open

Comments

@erikw
Copy link

erikw commented Dec 12, 2022

Thanks for providing this module.

I've used the PriorityQueue a bit and noticed something that looks like a bug to me. It seems like if the same element is inserted again after have being extracted once alrady, is not possible.

See this minimal example:

const PriorityQueue = require("algorithms/data_structures").PriorityQueue;

const q = new PriorityQueue();

// Inserting and extracting one time works as expected:
q.insert("a", 1);
console.log(q.isEmpty());
console.log(q.extract());
console.log(q.isEmpty());

// Inserting 'a' again does not work, queue will be empty and nothing to extract:
q.insert("a", 1);
console.log(q.isEmpty());
console.log(q.extract());

The outoupt of this is:

false
a
true
true
undefined

while the expected output is:

false
a
true
false
a

My system:

  • node v19.2.0.
  • macOS 13.0.1
@Semigradsky
Copy link

insert(item, priority) {
if (this._priority[item] !== undefined) {
return this.changePriority(item, priority);
}
this._priority[item] = priority;
super.insert(item);
}
extract(withPriority) {
const min = MinHeap.prototype.extract.call(this);
return withPriority
? min && {item: min, priority: this._priority[min]}
: min;
}

Looks like this._priority should be cleared in the extract function. Otherwise, super.insert will not be called.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants