// 최대 힙
class Heap {
constructor(list = []) {
this.list = list
for (let i = Math.floor(list.length / 2); i >= 0; i--) {
this.siftDown(i, list.length)
}
}
heapify(idx) {
const parent = Math.floor((idx - 1) / 2)
if (this.list[idx] > this.list[parent]) {
this.swap(idx, parent)
this.heapify(parent)
}
}
siftDown(idx, length) {
const left = idx * 2 + 1
const right = idx * 2 + 2
let largest = idx
if (left < length && this.list[left] > this.list[largest]) {
largest = left
}
if (right < length && this.list[right] > this.list[largest]) {
largest = right
}
if (idx !== largest) {
this.swap(largest, idx)
this.siftDown(largest, length)
}
}
insert(data) {
const length = this.list.length
this.list[length] = data
this.heapify(length)
}
delete() {
if (!this.list.length) {
return false
}
const item = this.list[0]
this.list[0] = this.list.pop()
this.siftDown(0, this.list.length)
return item
}
peek() {
return this.list
}
swap(indexOne, indexTwo) {
const temp = this.list[indexOne]
this.list[indexOne] = this.list[indexTwo]
this.list[indexTwo] = temp
}
}
const heap = new Heap([1, 2, 3, 4, 9, 6, 7, 8, 0])
heap.insert(99)
heap.insert(10)
heap.delete()
heap.peek() // [ 10, 9, 7, 4, 8, 6, 3, 1, 0, 2 ]