• 二叉堆的实现代码


    因为二叉堆满足完全二叉树,一颗高为h的完全二叉树有2^h到2^h-1个节点,那么就可以用数组来表示。




    public
    class HeapDemo<T extends Comparable<? super T>>{ public HeapDemo(){ this(DEFAULT_CAPACITY); } public HeapDemo(int capacity){ makeEmpty(); enlargeArray(capacity); } public HeapDemo(T[] items){ currentSize=items.length; array=(T[]) new Comparable[(currentSize+2)*11/10]; int i=0; for (T t : items) { array[i++]=t; } buildHeap(); } public void insert(T val){ if(currentSize==array.length-1){ enlargeArray(2*array.length-1); } int hole=++currentSize; for(array[0]=val;val.compareTo(array[hole/2])<0;hole/=2){ array[hole]=array[hole/2]; } array[hole]=val; } public T findMin(){ return array[1]; } public T deleteMin() { if(isEmpty()){ throw new RuntimeException("堆为空"); } T minnum=findMin(); array[1]=array[currentSize--]; percolateDown(1); return minnum; } public boolean isEmpty(){ return currentSize==0; } public void makeEmpty(){ for(int i=0;i<currentSize;i++){ array[currentSize]=null; } currentSize=0; } private static final int DEFAULT_CAPACITY=10; private int currentSize; private T[] array; private void percolateDown(int hole){ T tep=array[1]; for(int child=1;hole*2<currentSize;hole=child){ child=hole*2; if(array[child].compareTo(array[child+1])<0) child++; if(tep.compareTo(array[child])<0){ array[hole]=array[child]; }else{ break; } } array[hole]=tep; } private void buildHeap(){ for(int i=currentSize/2;i>0;i--){ percolateDown(i); } } private void enlargeArray(int newSize){ T[] oldArray=array; if(newSize<currentSize){ return; } array=(T[]) new Object[newSize]; for(int i=1;i<currentSize;i++){ array[i]=oldArray[i]; } } }
  • 相关阅读:
    frp最简配置 实现内网穿透(访问内网WEB服务器)
    frp最简配置 实现内网穿透(访问内网其他服务器SSH)
    Linux 进程树查看工具 pstree
    svn Server authz 配置示例(文件夹权限配置)
    centos7 安装 mysql5.7.25
    centos7中将tomcat注册为系统服务
    keepalived 配置文件解析
    datatables参数配置详解
    使用jquery.datatable.js注意事项
    ondblclick和dblclick区别
  • 原文地址:https://www.cnblogs.com/wxw7blog/p/7624032.html
Copyright © 2020-2023  润新知