SOURCE

class PQueue {
    constructor(compare = (a, b) => a - b) {
        this.compare = compare
        this.queue = []
    }

    // 新增数据
    offer(value) {
        this.queue.push(value)
        this._heapInsert()
    }

    // 弹出堆顶数据
    poll() {
        if (!this.queue.length) {
            return null
        }
        const top = this.queue.shift()
        this._heapify()
        return top
    }

    _swap(arr, index1, index2) {
        if (index1 === index2) {
            return
        }
        let temp = arr[index1]
        arr[index1] = arr[index2]
        arr[index2] = temp
    }

    _heapify() {
        let parent = 0
        let left = parent * 2 + 1
        while (left < this.queue.length) {
            let operator = (left + 1 < this.queue.length) && this.compare(this.queue[left + 1], this.queue[left]) > 0 ? left + 1 : left
            if (this.compare(this.queue[operator], this.queue[parent]) > 0) {
                this._swap(this.queue, operator, parent)
            }
            parent = operator
            left = parent * 2 + 1
        }
    }

    _heapInsert() {
        let child = this.queue.length - 1
        let parent = (child / 2) | 0
        while (this.compare(this.queue[child], this.queue[parent]) > 0) {
            this._swap(this.queue, child, parent)
            child = parent
            parent = (child / 2) | 0
        }
    }
}

let arr = [46, 12, 33, 72, 68, 19, 80, 33]
let queue = new PQueue()

for (let i = 0; i < 7; i++) {
    queue.offer(arr[i])
}

for (let i = 0; i < 7; i++) {
    let result = []
    result.push(queue.poll() + ',')
    document.write(result)
}
console 命令行工具 X clear

                    
>
console