其他分享
首页 > 其他分享> > 二叉堆和堆排序

二叉堆和堆排序

作者:互联网

二叉堆是一种特殊的二叉树。

// 创建最小堆
class MinHeap {
    constructor(compareFn = defaultCompare){
        this.compareFn = compareFn
        this.heap = []
    }
}
MinHeap.prototype.getLeftIndex = function(index){
    return 2 * index + 1
}
MinHeap.prototype.getRightIndex = function(index){
    return 2 * index + 2
}
MinHeap.prototype.getParentIndex = function(index){
    if(index === 0){
        return undefined
    }
    return Math.floor((index - 1) / 2)
}
MinHeap.prototype.insert = function(value){
    if(value != null){
        this.heap.push(value)
        this.shiftUp(this.heap.length - 1)
    }
}
MinHeap.prototype.shiftUp = function(index){
    let parentIndex = this.getParentIndex(index)
    while(index > 0 && this.heap[parentIndex] > this.heap[index]){
        swap(this.heap,parentIndex,index)
        index = parentIndex
        parentIndex = this.getParentIndex(index)
    }
}
MinHeap.prototype.size = function(){
    return this.heap.length
}
MinHeap.prototype.isEmpty = function(){
    return this.size() == 0
}
MinHeap.prototype.findMinimum = function(){
    return this.isEmpty() ? undefined : this.heap[0]
}
MinHeap.prototype.extract = function(){
    if(this.isEmpty()){
        return undefined
    }
    if(this.size() == 1){
        return this.heap.shift()
    }
    const removedValue = this.heap.shift()
    this.shiftDown(0)
    return removedValue
}
MinHeap.prototype.shiftDown = function(index){
    let element = index
    const left = this.getLeftIndex(index)
    const right = this.getRightIndex(index)
    const size = this.size()
    if(left < size && this.heap[element] - this.heap[left] > 0){
        element = left
    }else if(right < size && this.heap[element] - this.heap[right] > 0){
        element = right
    }
    if(index !== element){
        swap(this.heap,index,element)
        this.shiftDown(element)
    }
}

  

标签:function,index,return,堆排序,二叉,heap,MinHeap,prototype
来源: https://www.cnblogs.com/zhenjianyu/p/13237211.html