2
我不确定如何将项目插入到我的最大堆中,然后慢慢向上以使max heap属性保持不变。 如果heapArray已满,我已经引发异常,因此无法插入项目。将项目插入Max Heap
我没有使用JCF类或该程序的优先级队列。 我也引发了我的deleteMax方法,该方法删除堆的最大值并恢复堆,使max heap属性保持不变。
public class MaxIntHeap {
//my global var's
private int[] heapArray; // default size of 20 in constructor
private int lastOne; //equal to size of the array(heap)
private int size;
private int k;
public void heapInsert(int v) throws HeapException {
if(lastOne == heapArray.length - 1){
throw new HeapException("The value " + v + " cannot be inserted because the heap is FULL!");
}
else{ //This is where i am lost as to how i should insert
lastOne++; //size of lastOne is increased.
}
这是我的removeMax方法。
public int removeMax()throws HeapException {
if(size == 0){
throw new HeapException("The Heap is empty, therefore the Max value of the heap cannot be
removed.");
}
else{
int max = heapArray[0];
heapArray[0] = heapArray[lastOne];
lastOne--;
k = 0;
while(k > 0){
int j = k/2;
if(heapArray[k] < heapArray[j]){
swap(heapArray[k], heapArray[j]); //swap method...
k = j;
}
else
break;
}
return max;
}
}
任何帮助将不胜感激。谢谢!