Last active
September 20, 2018 07:48
-
-
Save RomanSteinberg/34e50b302f07cb61ef7ad11849cd45a0 to your computer and use it in GitHub Desktop.
Heap and priority queue
This file contains hidden or 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 Heap { | |
constructor() { | |
this.container = [null]; | |
} | |
isRoot(ind) { | |
return ind == 1; | |
} | |
swap(ind1, ind2) { | |
const tmp = this.container[ind1]; | |
this.container[ind1] = this.container[ind2]; | |
this.container[ind2] = tmp; | |
} | |
invalidWithParent(ind, parentInd) { | |
return parentInd > 0 && ind < this.container.length && this.container[ind] < this.container[parentInd]; | |
} | |
heapifyUp() { | |
let ind = this.container.length - 1; | |
let parentInd = Math.floor(ind/2); | |
while (!this.isRoot(ind) && this.invalidWithParent(ind, parentInd)) { | |
this.swap(ind, parentInd); | |
ind = parentInd; | |
parentInd = Math.floor(ind/2); | |
} | |
} | |
heapifyDown() { | |
let ind = 1; | |
while (ind < this.container.length) { | |
let nextInd = undefined; | |
if (this.invalidWithParent(2*ind, ind)) { | |
nextInd = 2*ind; | |
} | |
if (this.invalidWithParent(2*ind+1, ind) && this.container[2*ind+1] < this.container[2*ind]) { | |
nextInd = 2*ind+1; | |
} | |
if (!nextInd) { | |
break; | |
} | |
this.swap(ind, nextInd); | |
ind = nextInd; | |
} | |
} | |
add(item) { | |
this.container.push(item); | |
this.heapifyUp(); | |
} | |
getMin() { | |
return this.container[1]; | |
} | |
removeMin() { | |
this.swap(1, this.container.length-1); | |
this.container.pop(); | |
this.heapifyDown(); | |
} | |
} |
This file contains hidden or 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 ElementWithPriority { | |
constructor(item, priority) { | |
this.item = item; | |
this.priority = priority; | |
} | |
valueOf() { | |
return this.priority; | |
} | |
} | |
class PriorityQueue { | |
constructor() { | |
this.heap = new Heap(); | |
} | |
add(item, priority) { | |
this.heap.add(new ElementWithPriority(item, priority)); | |
} | |
getMin() { | |
return this.heap.getMin(); | |
} | |
removeMin() { | |
this.heap.removeMin(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment