我有一个只有 x 和 y 的 Point 对象,我有一个 Heap 数据结构,如下所示:
class MaxHeap{
public Point[] heap;
public int size;
public int maxsize;
public MaxHeap(int maxsize){
this.maxsize = maxsize;
this.size = 0;
heap = new Point[this.maxsize+1];
heap[0] = new Point(-1,-1); //Heap is empty
}
public int parent(int pos){
return pos /2;
}
public int leftChild(int pos){
return (2 * pos);
}
public int rightChild(int pos){
return (2 * pos) +1;
}
public boolean isLeaf(int pos){
if (pos >= (size / 2) && pos <= size){
return true;
}
return false;
}
public void swap (int fpos, int spos){
Point tmp;
tmp = heap[fpos];
heap[fpos] = heap[spos];
heap[spos] = tmp;
}
public void maxHeapify(int pos){
if (!isLeaf(pos)){
if (heap[pos].getY() < heap[leftChild(pos)].getY() || heap[pos].getY() < heap[rightChild(pos)].getY()){
swap(pos, leftChild(pos));
maxHeapify(leftChild(pos));
}
else{
swap(pos, rightChild(pos));
maxHeapify(rightChild(pos));
}
}
}
public void insert (Point p){
heap[++size] = p;
int current = size;
while (heap[current].getY() > heap[parent(current)].getY()){
swap(current, parent(current));
current = parent(current);
}
}
我正在尝试实现一种从堆中删除任何点的方法,而不是传统的删除它只是删除顶部的方法。我不完全确定如何去做。我在想我可以将 Point 的索引存储在 Point 内部的堆中。我不确定这是否有帮助。