Created
January 13, 2017 17:02
-
-
Save olegon/a3b9403aa2196d65649f7a47a06238e7 to your computer and use it in GitHub Desktop.
Implementação de PriorityQueue com Binary Heap, JavaScript ES6
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
/* | |
Implementação de PriorityQueue com Binary Heap. | |
JavaScript ES6 | |
*/ | |
class PrioriryQueue { | |
constructor (cmp = (a, b) => a > b) { | |
this.array = [null]; | |
this.cmp = cmp; | |
} | |
queue (value) { | |
const { array, cmp } = this; | |
// Adicionando valor | |
array.push(value); | |
// Equilibrando a árvore | |
let k = array.length - 1; | |
while (k > 1 && cmp(array[k], array[~~(k / 2)])) { | |
let c = array[k]; | |
array[k] = array[~~(k / 2)]; | |
array[~~(k / 2)] = c; | |
k = ~~(k / 2); | |
} | |
} | |
dequeue () { | |
const { array, cmp } = this; | |
if (array.length == 1) throw new Error("There aren't elements."); | |
if (array.length == 2) return array.pop(); | |
const value = array[1]; | |
// Equilibrando a árvore | |
array[1] = array.pop(); | |
let k = 1; | |
while (k * 2 <= array.length - 1) { | |
let j = k * 2; | |
if (j < array.length && cmp(array[j + 1], array[j])) j++; | |
if (cmp(array[k], array[j])) break; | |
let c = array[k]; | |
array[k] = array[j]; | |
array[j] = c; | |
k = j; | |
} | |
return value; | |
} | |
} | |
var pq = new PrioriryQueue((a, b) => { | |
return a > b; | |
}); | |
pq.queue(3); | |
pq.queue(1); | |
pq.queue(7); | |
pq.queue(2); | |
console.log(pq.dequeue()); | |
console.log(pq.dequeue()); | |
console.log(pq.dequeue()); | |
pq.queue(11); | |
pq.queue(-3); | |
console.log(pq.dequeue()); | |
console.log(pq.dequeue()); | |
console.log(pq.dequeue()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment