zoukankan      html  css  js  c++  java
  • 大顶堆的实现

    // 创建堆
    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);
  • 相关阅读:
    json学习系列(1)-使用json所要用到的jar包下载
    Java 时间架构图
    时间纪元与时区介绍
    HTML5 Canvas 绘制库存变化折线
    HTML5 Canvas 笛卡尔坐标系转换尝试
    像孩童一样欣喜的看着自己的成长
    《老炮儿》结尾貌似历史上的一幕
    很多人还在守着金饭碗要饭
    还是用文本编辑器编程让人愉悦
    Node.js 网页爬虫再进阶,cheerio助力
  • 原文地址:https://www.cnblogs.com/strivegys/p/13214433.html
Copyright © 2011-2022 走看看