부모 노드 찾는 법
class MaxBinaryHeap(){
constructor(){
this.values = [];
}
insert(element){
this.values.push(element);
this.bubbleUp();
}
bubbleUp(){
let idx = this.values.length-1;
const element = this.values[idx];
while(idx > 0){
let parentIdx = Math.floor((idx -1) /2);
let parent = this.values[parentIdx];
if(element < parent) break;
this.values[idx] = parent;
this.values[parentIdx] = element;
idx = parentIdx;
}
class MaxBinaryHeap(){
constructor(){
this.values = [];
}
insert(element){
this.values.push(element);
this.bubbleUp();
}
bubbleUp(){
let idx = this.values.length-1;
const element = this.values[idx];
while(idx > 0){
let parentIdx = Math.floor((idx -1) /2);
let parent = this.values[parentIdx];
if(element < parent) break;
this.values[idx] = parent;
this.values[parentIdx] = element;
idx = parentIdx;
}
extraMax(){
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;
const length = this.values.length;
const element = this.values[0]
while(true){
let leftChildIdx = idx * 2 +1;
let rightChildIdx = idx *2 +2;
let leftChild, rightChild;
let swap = null;
if(leftChildIdx < length){
leftChild = this.values[leftChildIdx];
if(leftChild > element){
swap = leftChildIdx;
}
}
if(
(swap === null && rightChild > element) ||
(swap !== null && rightChild > leftChild)
){
swap = rightChildIdx;
}
}
if(swap === null) break;
this.value[idx] = this.values[swap];
this.values[swap] = element;
idx = swap;
}
}
}
우선순위 큐 : 각 요소가 우선순위를 가지고 있는 데이터 구조다.
더 높은 우선순위를 가진 요소들이 먼저 처리된다.
=>
언제사용 하는가?