class MaxPQ<Item> {
private N = 0
private pq: Item[] = []
exch = (a: Item[], i: number, j: number): void => {
const temp: Item = a[i]
a[i] = a[j]
a[j] = temp
}
swim = (k: number) => {
while (k > 1 && this.pq[k] > this.pq[Math.floor(k / 2)]) {
this.exch(this.pq, k, Math.floor(k / 2))
k = Math.floor(k / 2)
}
}
sink = (k: number) => {
while (2 * k <= this.N) {
let i = 2 * k
if (i < this.N && this.pq[i + 1] > this.pq[i]) i++
if (this.pq[k] >= this.pq[i]) break
this.exch(this.pq, k, i)
k = i
}
}
insert(item: Item): void {
this.pq[++this.N] = item
this.swim(this.N)
}
delMax(): Item {
const res = this.pq[1]
this.pq[1] = this.pq[this.N]
this.pq[this.N--] = null
this.sink(1)
return res
}
}
const a = [5, 3, 6, 1, 543, 24, 56, 123, 444, 325]
const pq = new MaxPQ()
a.forEach((item) => pq.insert(item))
console.log(pq.delMax(), pq.delMax())