堆的实现主要是要利用完成二叉树和数组的装换关系。堆的操作里,最核心的就是向上和向下的比较交换。
public class MaxHeap {
private int [] values;
private int limit;
private int heapSize;
public MaxHeap(int num){
this.values = new int[num];
this.limit = num;
}
//往堆里面插入元素
public void push(int value){
if (heapSize == limit){
throw new RuntimeException("堆已满");
}
values[heapSize] = value;
insertHeap(values,heapSize++);
}
//取出堆里面最大的元素
public int pop(){
if (heapSize == 0){
throw new RuntimeException("堆里没有数了");
}
int answer = values[0];
swap(values,0,--heapSize);
downHeap(values,0,heapSize);
return answer;
}
//往上走 往下走
public void insertHeap(int [] arr, int index){
//当插入的节点比父节点大的话 就交换
while (arr[index] > arr[(index-1)/2]){
swap(arr,index,(index-1)/2);
//不断往上走
index =(index-1)/2;
}
}
public void downHeap(int [] arr, int index, int heapSize){
int left =2*index+1;
while (left arr[left] ?left+1:left;
largest = arr[largest]>arr[index] ? largest:index;
if (largest ==index){
break;
}
swap(arr,largest,index);
index = largest;
left = 2 *index+1;
}
}
private void swap(int [] arr, int i, int j){
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
public static void main(String[] args) {
MaxHeap heap = new MaxHeap(5);
heap.push(10);
heap.push(13);
System.out.println(heap.pop());
System.out.println(heap.pop());
heap.pop();
}
}



