Last active
May 8, 2017 20:46
-
-
Save akilism/9039dd41a611e56baec6 to your computer and use it in GitHub Desktop.
Minimum Priority Queue ES6 Class syntax.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class MinPQ { | |
constructor(comparator) { | |
this.comparator = comparator || MinPQ.compare; | |
this.items = []; | |
this.n = 0; | |
} | |
insert(value) { | |
this.items[++this.n] = value; | |
this.swim(this.n); | |
} | |
isEmpty() { return this.n === 0; } | |
size() { return this.n; } | |
less(a, b) { return this.comparator(this.items[a], this.items[b]) < 0; } | |
greater(a, b) { return this.comparator(this.items[a], this.items[b]) > 0; } | |
exch(a, b) { | |
let x = this.items[a]; | |
this.items[a] = this.items[b]; | |
this.items[b] = x; | |
} | |
popMin() { | |
if(this.isEmpty()) { throw new Error('No Items on Priority Queue'); } | |
this.exch(1, this.n); | |
let min = this.items[this.n--]; | |
this.sink(1); | |
return min; | |
} | |
min() { | |
return this.items[1]; | |
} | |
swim(k) { | |
while(k > 1 && this.greater(Math.floor(k/2), k)) { | |
this.exch(k, Math.floor(k/2)); | |
k = Math.floor(k/2); | |
} | |
} | |
sink(k) { | |
while(2*k <= this.n) { | |
let k2 = 2*k; | |
if(k2 < this.n && this.greater(k2, k2+1)) { k2++; } | |
if(!this.greater(k, k2)) { break; } | |
this.exch(k, k2); | |
k = k2; | |
} | |
} | |
static compare(valA, valB) { | |
if(valA > valB) { return 1; } | |
if(valA === valB) { return 0; } | |
if(valA < valB) { return -1; } | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment