大顶堆的实现

// 创建堆
function CreateHeap(MaxSize,MaxData) {
    this.MaxSize = MaxSize;
    this.Heap = new Array();
    this.Heap[0] = MaxData   // 定义" 哨兵 " 为大于堆中所有可能元素的值
    this.isFull = CreateHeap.isFull
    this.Insert = CreateHeap.Insert
    this.isEmpty = CreateHeap.isEmpty
    this.DeleteMax = CreateHeap.DeleteMax
}

CreateHeap.isFull = function() {
    return this.Heap.length == this.MaxSize;
}
CreateHeap.Insert = function(element) {
    let i;
    if(this.isFull()) {
        console.error("最大堆已满")
        return -1;
    }

    this.Heap.push(element);  //长度+1
    i = this.Heap.length - 1;

    for(;this.Heap[Math.floor(i/2)] < element;i=Math.floor(i/2)) {  // 进行向下取整
        this.Heap[i] = this.Heap[Math.floor(i/2)]
    }

    this.Heap[i] = element;
    return this;
}
CreateHeap.isEmpty = function() {
    return (this.Heap.length - 1 == 0)
}
CreateHeap.DeleteMax = function() {
    // parent 代表 父节点,child 代表 子节点,maxItem 代表 删除的最大值,element 代表 堆中最后一个值
    let parent, child, maxItem, element; 
    if(this.isEmpty()) {
        console.error("最大堆已空");
        return -2;
    }

    maxItem = this.Heap[1];
    element = this.Heap[this.Heap.length - 1];
    this.Heap.length--;

    for(parent = 1; parent*2<=this.Heap.length-1; parent=child) {  // 判断是否有左子树,如果没有直接跳过,进行赋值
        child = parent * 2;
        if((child != this.Heap.length-1) && (this.Heap[child] < this.Heap[child +1])) {        // 找出两个节点的最大值
            child++
        }
        if(element > this.Heap[child]) {
            break;
        } else {
            this.Heap[parent] = this.Heap[child];   // 将子节点中的最大值,放到parent位置
        }
    }
    this.Heap[parent] = element;

    return maxItem;
}


let heap = new CreateHeap(8,1000);
heap.Insert(10).Insert(14).Insert(16).Insert(15).Insert(8).Insert(11)
console.log(heap.Heap);
console.log(heap.DeleteMax());
console.log(heap.Heap);

 

posted @ 2020-06-30 16:21  guogrant  阅读(187)  评论(0编辑  收藏  举报