Last active
October 12, 2019 09:38
-
-
Save evan-moon/08840d108f0ed357036e298f999592be to your computer and use it in GitHub Desktop.
MaxHeap 구현체
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 MaxHeap { | |
constructor (maxLevel = 1) { | |
this.nodes = []; | |
} | |
// phase2 | |
insert (value) { | |
this.nodes.push(value); | |
this.bubbleUp(); | |
} | |
bubbleUp (index = this.nodes.length - 1) { | |
if (index < 1) { | |
return; | |
} | |
const currentNode = this.nodes[index]; | |
const parentIndex = Math.floor((index - 1) / 2); | |
const parentNode = this.nodes[parentIndex]; | |
if (parentNode >= currentNode) { | |
return; | |
} | |
this.nodes[index] = parentNode; | |
this.nodes[parentIndex] = currentNode; | |
index = parentIndex; | |
this.bubbleUp(index); | |
} | |
extract () { | |
const max = this.nodes[0]; | |
this.nodes[0] = this.nodes.pop(); | |
this.trickleDown(); | |
return max; | |
} | |
trickleDown (index = 0) { | |
const leftChildIndex = 2 * index + 1; | |
const rightChildIndex = 2 * index + 2; | |
const length = this.nodes.length; | |
let largest = index; | |
if (leftChildIndex <= length && this.nodes[leftChildIndex] > this.nodes[largest]) { | |
largest = leftChildIndex; | |
} | |
if (rightChildIndex <= length && this.nodes[rightChildIndex] > this.nodes[largest]) { | |
largest = rightChildIndex; | |
} | |
if (largest !== index) { | |
[this.nodes[largest], this.nodes[index]] = [this.nodes[index], this.nodes[largest]]; | |
this.trickleDown(largest); | |
} | |
} | |
} | |
const heap = new MaxHeap(); | |
heap.insert(1); | |
heap.insert(3); | |
heap.insert(23); | |
heap.insert(2); | |
heap.insert(10); | |
heap.insert(32); | |
heap.insert(9); | |
const length = heap.nodes.length; | |
console.log(length); | |
for (let i = 0; i < length; i++) { | |
console.log('MAX_VALUE = ', heap.extract()); | |
console.log('HEAP = ', heap.nodes); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment