class MaxBinaryHeap{ constructor(){ this.values = [] } }
bubbleUp(){ let currentIndex = this.values.length-1 let parentIndex = Math.floor((currentIndex-1)/2) while(true){ parentIndex = Math.floor((currentIndex-1)/2) if(this.values[parentIndex] < this.values[currentIndex]){ [this.values[parentIndex],this.values[currentIndex]] = [this.values[currentIndex],this.values[parentIndex]] currentIndex = parentIndex }else break } } insert(val){ this.values.push(val) this.bubbleUp() return this }
-최대 이진 힙일경우 최대값(루트) 최소 이진 힙일경우 최소값(루트)를 제거
sinkDown(){ let idx = 0 let len = this.values.length let element = this.values[0] while(true){ let leftChildIdx = idx*2 + 1 let rightChildIdx = idx*2 + 2 let leftChild,rightChild let swap = null if(leftChildIdx < len){ leftChild = this.values[leftChildIdx] if(leftChild > element){ swap = leftChildIdx } } if(rightChildIdx < len){ rightChild = this.values[rightChildIdx] if((swap===null && rightChild > element) || (swap!==null && rightChild > element)){ swap = rightChildIdx } } if(swap === null) break this.values[idx] = this.values[swap] this.values[swap] = element idx = swap } } extractMax(){ let max = this.values[0] let end = this.values.pop() if(this.values.length !== 0){ this.values[0] = end } this.sinkDown() return max }
class Node{ constructor(val,priority){ this.val = val this.priority=priority } } class PriorityQueue{ constructor(){ this.values = [] } enqueue(val,priority){ let newNode = new Node(val,priority) this.values.push(newNode) this.bubbleUp() } bubbleUp(){ let idx = this.values.length-1 let element = this.values[idx] while(idx > 0){ let parentIdx = Math.floor((idx-1)/2) let parent = this.values[parentIdx] if(parent.priority > element.priority) break; this.values[parentIdx] = element this.values[idx] = parent idx = parentIdx } } dequeue(){ const max = this.values[0] const end = this.values.pop() if(this.values.length !== 0){ this.values[0] = end this.sinkDown() } return max } sinkDown(){ let idx = 0 let element = this.values[0] let length = this.values.length while(true){ let swap = null let leftIdx = idx*2+1 let rightIdx = idx*2+2 if(leftIdx < length ){ let leftChild = this.values[leftIdx] if(element.priority < leftChild.priority){ swap = leftIdx } } if(rightIdx <length){ let rightChild = this.values[rightChild] if((swap === null && element.priority < rightChild.priority)|| (swap!==null && element.priority < rightChild.priority)){ swap = rightIdx } } if(swap === null) break this.values[idx] = this.values[swap] this.values[swap] = element idx = swap } } }