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);
  • 相关阅读:
    springboot 2.2.1默认跳到登录页
    Shiro 认证失败返回JSON
    【问题】:spring cloud sleuth日志组件冲突问题
    转载:springboot 配置logback日志,超详细
    Rancher探秘二:安装Rancher
    Rancher探秘一:初识Rancher
    Spring Cloud 微服务六:调用链跟踪Spring cloud sleuth +zipkin
    Spring Cloud 微服务五:Spring cloud gateway限流
    Spring Cloud 微服务四:熔断器Spring cloud hystrix
    chrome remoting/ chromoting 分析#1
  • 原文地址:https://www.cnblogs.com/strivegys/p/13214433.html
Copyright © 2011-2022 走看看