//出堆
public int pop(int[] heap){
if(heap[0]<=0){
throw new RuntimeException("堆空了");
}
int re = heap[1];
heap[1] = heap[heap[0]];
heap[0]--;
downAdjustment(heap);
return re;
}
//建堆,为方便计算,数组下标为0用来存放当前元素的个数
public void buildMinHeap(int heap[],int element){
heap[0]++;
heap[heap[0]] = element;
upAdjustment(heap);
}
//向上调整,入堆后的操作,例如插入值是e,如果e的父元素大于e则交换,重复此操作直到找到合适位置
public void upAdjustment(int heap[]){
int i = heap[0];
while (i>1){
//父元素的位置
int parent = i/2;
int temp = heap[i];
if(heap[i] < heap[parent]){
heap[i] = heap[parent];
heap[parent] = temp;
i=parent;
}else {
break;
}
}
}
//向下调整,出堆后最后一个元素e放到堆顶向下调整到合适位置,每次找e的子元素,若最小子元素小于e,则e与其交换,重复此操作直到找到合适位置
public void downAdjustment(int heap[]){
int i=1;
int len = heap[0];
while ((i<<1)<=len) {
//子元素位置
int l = i<<1;
int r = l+1;
int index = i;
if(heap[l] < heap[i]){
index = l;
}
if(r<=len && heap[r]<heap[i] && (heap[r] < heap[l] || index!=l)){
index = r;
}
if(index==i){
break;
}
int temp = heap[i];
heap[i] = heap[index];
heap[index] = temp;
i = index;
}
}
堆的Java实现
最新推荐文章于 2023-07-01 07:37:05 发布