public class Heap{ private int[] data; //存放数据 private int size; //堆的最大容量 private int currentPos;//当前空闲游标 public Heap(){ this(10); } public Heap(int size){ this.size = size; this.data = new int[this.size + 1]; this.currentPos = 1; } public void add(int value){ if(this.currentPos > this.size){ throw new IndexOutOfBoundsException(Integer.toString(this.size)); } if(this.currentPos == 1){ this.data[this.currentPos++] = value; }else{ int parent = this.currentPos / 2; int current = this.currentPos; while(parent >= 1){ if(this.data[parent] < value){ this.data[current] = this.data[parent]; current = parent; parent = parent / 2; }else{ break; } } this.data[current] = value; this.currentPos++; } } public int delete(){ if(this.currentPos <= 0){ throw new IndexOutOfBoundsException(Integer.toString(this.currentPos)); } int valueReturn = this.data[1]; int temp = data[--this.currentPos]; int parent = 1; int current = 2; int maxValue = 0; while(current < this.currentPos){ maxValue = this.data[current]; if((current + 1) < this.currentPos && this.data[current + 1] > maxValue){ maxValue = this.data[++current]; } if(temp >= maxValue){ break; }else{ this.data[parent] = this.data[current]; parent = current; current *= 2; } } this.data[parent] = temp; return valueReturn; } }