Skip to content

Instantly share code, notes, and snippets.

@zlrlo
Created May 23, 2024 16:38
Show Gist options
  • Select an option

  • Save zlrlo/14aa251b5f472e01452c8bf4fd0d07d7 to your computer and use it in GitHub Desktop.

Select an option

Save zlrlo/14aa251b5f472e01452c8bf4fd0d07d7 to your computer and use it in GitHub Desktop.
[JS] Min Heap 구현
class MinHeap {
constructor() {
this.heap = [null];
}
push(value) {
this.heap.push(value);
let currentIndex = this.heap.length - 1;
let parentIndex = Math.floor(currentIndex / 2);
while (parentIndex !== 0 && this.heap[parentIndex] > value) {
const temp = this.heap[parentIndex];
this.heap[parentIndex] = value;
this.heap[currentIndex] = temp;
currentIndex = parentIndex;
parentIndex = Math.floor(currentIndex / 2);
}
}
pop() {
const returnValue = this.heap[1];
this.heap[1] = this.heap.pop();
let currentIndex = 1;
let leftIndex = 2;
let rightIndex = 3;
while (this.heap[currentIndex] > this.heap[leftIndex] ||
this.heap[currentIndex] > this.heap[rightIndex]) {
if (this.heap[leftIndex] > this.heap[rightIndex]) {
const temp = this.heap[currentIndex];
this.heap[currentIndex] = value;
this.heap[rightIndex] = temp;
currentIndex = rightIndex;
} else {
const temp = this.heap[currentIndex];
this.heap[currentIndex] = value;
this.heap[leftIndex] = temp;
currentIndex = leftIndex;
}
leftIndex = currentIndex * 2;
rightIndex = currentIndex * 2 + 1;
}
return returnValue;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment