Skip to content

Instantly share code, notes, and snippets.

@pinkmomo027
Created June 29, 2018 23:55
Show Gist options
  • Save pinkmomo027/2feab041610af5e686b052f727e0bca0 to your computer and use it in GitHub Desktop.
Save pinkmomo027/2feab041610af5e686b052f727e0bca0 to your computer and use it in GitHub Desktop.
trying out PQ
class QElement {
constructor (value, priority) {
this.value = value;
this.priority = priority
}
}
class PQ {
constructor () {
this.elements = ['root'];
}
enqueue(e) {
this.elements.push(e);
this.swim(this.elements.length - 1);
}
swim(index) {
while(index > 1 && this.lower(Math.floor(index / 2), index)) {
this.swap(Math.floor(index / 2), index);
index = Math.floor(index / 2);
}
}
lower(i1, i2) {
return this.elements[i1].priority < this.elements[i2].priority;
}
swap(i1, i2) {
let tmp = this.elements[i1];
this.elements[i1] = this.elements[i2];
this.elements[i2] = tmp;
}
sink(index) {
let child = index * 2;
while(child < this.elements.length) {
// find bigger child
if ((child + 1 < this.elements.length) && this.lower(child, child + 1)) {
child++;
}
if (this.lower(index, child)) {
this.swap(index, child);
index = child;
} else {
break;
}
}
}
delMax() {
this.swap(1, this.elements.length - 1);
this.sink(1);
return this.elements.pop();
}
isEmpty() {
return this.elements.length == 1;
}
}
let queue = new PQ();
queue.enqueue(new QElement('xx', 10));
queue.enqueue(new QElement('xx', 13));
queue.enqueue(new QElement('xx', 8));
queue.enqueue(new QElement('xx', 28));
queue.enqueue(new QElement('xx', 2));
queue.enqueue(new QElement('xx', 50));
console.log(queue);
queue.delMax();
console.log(queue);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment