buildHeap方法不起作用,我多次检查了代码,但没有得到。我认为问题出在percolateDown方法上,但我不知道是哪一种。 buildHeap方法不起作用,我多次检查了代码,但没有得到。我认为问题出在percolateDown方法上,但我不知道是哪一种。 buildHeap方法不起作用,我多次检查了代码,但没有得到。我认为问题出在percolateDown方法上,但我不知道是哪一种。 buildHeap方法不起作用,我多次检查了代码,但没有得到。我认为问题出在percolateDown方法上,但我不知道是哪一种。 buildHeap方法不起作用,我多次检查了代码,但没有得到。我认为问题出在percolateDown方法上,但我不知道是哪一种。
public class DHeap<T extends Comparable>{
private int size;
private T[] array;
private int d;
public DHeap(int d){
size = 0;
this.d = d;
array = (T[]) new Comparable[10];
}
public DHeap(int initialSize, int d){
size = 0;
this.d = d;
array = (T[]) new Comparable[initialSize];
}
private void ensureCapacity(int newCapacity){
T[] newArray = Arrays.copyOf(array, newCapacity);
array = newArray;
}
public boolean isEmpty(){
return size == 0;
}
public void insert(T item) {
if(size == array.length - 1){
ensureCapacity(array.length * 2);
}
array[size++] = item;
percolateUp(size - 1);
}
public T delete(int index){
if(!isEmpty()){
T indexElement = array[index];
array[index] = array[size - 1];
size--;
percolateDown(index);
return indexElement;
}else{
return null;
}
}
public T deleteMin(){
T min = array[0];
delete(0);
return min;
}
public void buildHeap(T[] items){
size = items.length;
for(int i = 0; i<items.length; i++){
array[i] = items[i];
}
for(int j = size/2; j > 0; j--){
percolateDown(j);
}
}
public void printHeap(){
System.out.println("\n Heap = ");
for(int i = 0; i < size; i++){
System.out.print(array[i] + " ");
}
System.out.println();
}
private int parent(int i){
return (i-1)/d;
}
private int kThChild(int i, int k){
return d*i+k;
}
private int minChild(int index){
int bestChild = kThChild(index, 1);
int k = 2;
int pos = kThChild(index, k);
while((k <= d) && (pos < size)){
if(array[pos].compareTo(array[bestChild]) < 0){
bestChild = pos;
}
pos = kThChild(index, k++);
}
return bestChild;
}
private void percolateUp(int index){
T tmp = array[index];
while(index > 0 && tmp.compareTo(array[parent(index)]) < 0){
array[index] = array[parent(index)];
index = parent(index);
}
array[index] = tmp;
}
private void percolateDown(int index){
int child;
T tmp = array[index];
while(kThChild(index, 1) < size){
child = minChild(index);
if(array[child].compareTo(tmp) < 0)
array[index] = array[child];
else
break;
index = child;
}
array[index] = tmp;
}
}