public void addToSort(int data) {
maxHeap[++size] = data;
int current = size;
while (maxHeap[current] > maxHeap[parent(current)]) {
swap(current, parent(current));
current = parent(current);
}
}
public int pollToHeap() {
int max = maxHeap[1];
maxHeap[1] = maxHeap[size--];
int current = size;
while (maxHeap[current] > maxHeap[parent(current)]) {
swap(current, parent(current));
current = parent(current);
}
return max;
}
데이터 입력 시 바로 정렬되고, 출력 시 바로 재정렬되게 구현
기준 위치에 따라 값을 계속 비교하고 스왑만 해주면 된다.
public int pollToHeap() { // 최대 힙 제거 후 힙 재조정
int max = maxHeap[1];
maxHeap[1] = maxHeap[size--];
heapify(1);
return max;
}
public void heapify(int i) {
int leftChild = i * 2;
int rightChild = (i * 2) + 1;
int lastNode = 0;
if (rightChild > size) { // 핵심
return;
}
if (maxHeap[leftChild] > maxHeap[rightChild]) {
lastNode = leftChild;
} else {
lastNode = rightChild;
}
if (maxHeap[i] >= maxHeap[lastNode]) {
return;
}
swap(i, lastNode);
heapify(lastNode);
}
첫 데이터 제거 시 잘 되는 것 처럼 보였는데 다시보니 인덱스 감소랑 스왑이 안됨
완전 이진 트리이기 때문에 rightChild만 인덱스 체크 해주고 매번 새로운 루트가 되는
마지막 노드만 재귀를 통해 재정렬하면 된다.
public static void main(String[] args) {
PriorityQueue<Integer> pq = new PriorityQueue<>(Collections.reverseOrder());
Random rand = new Random();
for (int i = 0; i <= 10; i++) {
pq.offer(rand.nextInt(20));
}
for (Integer i : pq) {
System.out.print(i + " ");
}
System.out.println();
System.out.println(pq.poll());
for (Integer i : pq) {
System.out.print(i + " ");
}
}