public void percolateDown(int i){
int l,r,max,temp;
l = leftChild(i);
r = rightChild(i);
if(l != -1 && this.array[l] > this.array[i]){
max = l;
}else{
max = i;
}
if( r != -1 && this.array[r] > this.array[max]){
max = r;
}
if(max != i){
temp = this.array[i];
this.array[i] = this.array[max];
this.array[max] = temp;
}
percolate(max);
}
void resizeHeap(){
int[] array_old = new int[this.capacity];
System.out.arrayCopy(this.array,0,array_old,this.count-1);
this.array = new int[this.capacity*2];
if(this.array == null){
system.out.println("Memory error!");
return;
}
for(int i = 0;i< this.capacity;i++){
this.array[i] = array_old[i];
}
this.capacity *2;
array_old = null;
}
void buildHeap(Heap h,int[] a,int n){
if(h == null){
return;
}
while(n > this.capacity){
resizeHeap();
}
for(int i = 0; i < n; i++){
h.array[i] = a[i];
}
this.count = n;
for(int i = (n-1)/2; i>=0; i--){
percolate(i);
}
}
数组建堆
最新推荐文章于 2024-09-26 21:24:51 发布