实现一波堆
package heap;
import java.util.Arrays;
import java.util.Comparator;
public class HeapQueue<E extends Comparable> {
private E[] arr;
private int size = 0;
private int capacity = 10;
Comparator<E> comparable;
public HeapQueue(int capacity) {
this.capacity = capacity;
arr = (E[]) new Object[capacity];
size = 0;
}
public HeapQueue(int capacity, Comparator<E> comparable) {
this.capacity = capacity;
this.comparable = comparable;
arr = (E[]) new Object[capacity];
size = 0;
}
public HeapQueue(E[] arr) {
this.arr = arr;
this.size = arr.length;
this.capacity = arr.length;
buildHeap(arr);
}
public HeapQueue(E[] arr,Comparator<E> comparable) {
this.arr = arr;
this.size = arr.length;
this.capacity = arr.length;
this.comparable = comparable;
buildHeap(arr);
}
private void buildHeap(E[] arr){
int child = (size - 2)/2;
while(child >= 0){
shiftDown(arr,child);
child--;
}
}
public void offer(E val){
arr[size++] = val;
shiftDown(arr,size - 1);
}
public E poll() throws Exception {
if(size < 1) throw new Exception("error : size = "+ size);
E old = arr[0];
arr[0] = arr[size - 1];
size --;
adjustDown(arr,0);
return old;
}
public E peek() throws Exception {
if(size < 1) throw new Exception("error : size = "+ size);
return arr[0];
}
private void shiftDown(E[] heap,int index){
if(comparable == null) shiftDownWithNo(heap,index);
else shiftDownWithOne(heap,index);
}
private void adjustDown(E[] heap,int index){
if(comparable == null) adjustDownNo(heap,index);
else adjustDownWithOne(heap,index);
}
private void adjustDownNo(E[] heap,int index){
int cur = index;
int parent = index;
while(parent >= 0){
parent = cur >> 1;
if(arr[cur].compareTo(parent) >= 0){
break;
}
swap(arr,cur,parent);
cur = parent;
}
}
private void adjustDownWithOne(E[] heap,int index){
int cur = index;
int parent = index;
while(parent >= 0){
parent = cur >> 1;
if(comparable.compare(arr[cur],arr[parent]) >= 0){
break;
}
swap(arr,cur,parent);
cur = parent;
}
}
private void shiftDownWithNo(E[] heap,int index){
int cur = index;
int leftChild = index * 2 + 1;
while(leftChild < size){
if(leftChild+ 1 < size && heap[leftChild].compareTo(heap[leftChild+1]) > 0){
leftChild++;
}
if(heap[cur].compareTo(heap[leftChild]) <= 0){
break;
}
swap(heap,cur,leftChild);
cur = leftChild;
leftChild = leftChild * 2 + 1;
}
}
private void shiftDownWithOne(E[] heap,int index){
int cur = index;
int leftChild = index * 2 + 1;
while(leftChild < size){
if(leftChild+ 1 < size && comparable.compare(heap[leftChild],heap[leftChild+1]) > 0){
leftChild++;
}
if(comparable.compare(heap[cur],heap[leftChild]) <= 0){
break;
}
swap(heap,cur,leftChild);
cur = leftChild;
leftChild = leftChild * 2 + 1;
}
}
private void swap(E[] arr,int i,int j){
E e = arr[i];
arr[i] = arr[j];
arr[j] = e;
}
public int size(){
return size;
}
public static void main(String[] args) {
Integer[] arr = { 1,5,3,8,7,6 };
HeapQueue<Integer> heap = new HeapQueue<>(arr,((o1, o2) -> o2 - o1));
System.out.println(Arrays.toString(arr));
}
}