向下调整
class creatH {
public int[] elem;
public int usedSize;
public creatH(){
this.elem = new int[10];
}
//根节点从0开始编号的情况下
//parent每棵树的根节点,len每棵树的调整的结束位置
public void shiftDown(int parent,int len){
int child = 2*parent+1;
while(child < len){//至少有一个孩子
if(child+1 < len && elem[child] < elem[child+1]){
child++;
}else{
if(elem[child] > elem[parent]){
int tmp = elem[parent];
elem[parent] = elem[child];
elem[child] = tmp;
parent = child;
child = parent*2+1;
}else{
break;
}
}
}
}
public void creatHeap(int[] arr){
for (int i = 0; i < arr.length; i++) {
elem[i] = arr[i];
usedSize++;
}
for (int parent = (usedSize-1-1)/2; parent >= 0; parent--) {
//调整
shiftDown(parent,usedSize);
}
}
}
向上调整
public void shiftUp(int child){
int parent = (child-1)/2;
while(child > 0){
if(elem[child] > elem[parent]){
int tmp = elem[child];
elem[child] = elem[parent];
elem[parent] = tmp;
parent = (child-1)/2;
}else{
break;
}
}
}
public void offer(int child,int val){
if(isFull()){
//扩容
elem = Arrays.copyOf(elem,2*elem.length);
}
elem[usedSize++] = val;
//传入的是usedSize-1
shiftUp(usedSize-1);
}
public boolean isFull(){
return usedSize == elem.length;
}
出队列,返回队首元素
public boolean isEmpty(){
return usedSize == 0;
}
public int poll(){
if(isEmpty()){
throw new RuntimeException("优先级队列为空!");
}
int tmp = elem[0];//每次都出最大或最小的
elem[0] = elem[usedSize-1];
elem[usedSize-1] = tmp;
usedSize--;
shiftDown(0,usedSize);
return tmp;
}
//返回队首元素
public int peek(){
if(isEmpty()){
throw new RuntimeException("优先级队列为空!");
}
return elem[0];//0下标就是队首元素
}