우선 순위 대기열 (힙)에서 작업 중이며 기본 근거가 있다고 생각합니다. 내 방법은 모두 대부분의 부분에 의미가 있지만 내 bubbleDown
및 deleteMin
방법에 정말 고심한다고 생각합니다.우선 순위 대기열 힙 : 고정 bubbleDown 메소드
public class Heap {
private int n;
private Node[] s;
public Heap() {
s = new Node[128];
n =0;
}
public boolean isEmptySet() {
return (n == 0);
}
public Node findMin() {
return s[0];
}
public void insert(Node p) {
s[n] = p;
n = n+1;
bubbleUp(n - 1); // needs to subtract 1 because we do the addition
}
public void bubbleUp(int index) {
if (index == 0) {
return index;
}
else if (index > 0) {
int parentIndex = (index - 1)/2; // Might not need to subtract 1
if (s[index].getKey() < s[parentIndex].getKey()) {
swapNode(index, parentIndex);
bubbleUp(parentIndex);
}
}
}
public void swapNode(int index, int parentIndex) {
Node temp = s[index];
s[index] = s[parentIndex];
s[parentIndex] = temp;
}
public void deleteMin(Node p) {
n = n - 1;
bubbleDown(s[0], s[n]);
return s[n];
}
public void bubbleDown(int index) {
if (index < 0) {
int leftChildIndex = (i*2) + 1;
int rightChildIndex = (i*2) + 2;
if (s[index].getKey() > s[leftChildIndex].getKey()) {
swapNode(index, leftChildIndex);
bubbleDown(leftChildIndex);
} else if (s[index].getKey() < s[leftChildIndex].getKey() && s[index].getKey() > s[rightChildIndex].getKey()) {
swapNode(index, rightChildIndex);
bubbleDown(rightChildIndex);
}
}
}
}