ํ(Heap)์ ์์ ์ด์ง ํธ๋ฆฌ(Complete Binary Tree) ๊ธฐ๋ฐ์ ์๋ฃ๊ตฌ์กฐ๋ก, ์ต๋๊ฐ ๋๋ ์ต์๊ฐ์ ๋น ๋ฅด๊ฒ ์ฐพ์ ์ ์๋๋ก ๊ตฌ์ฑ๋ ํธ๋ฆฌ์ด๋ค.
๋ถ๋ชจ ๋
ธ๋๊ฐ ์์ ๋
ธ๋๋ณด๋ค ํฌ๊ฑฐ๋ ์๋ค๋ ํน์ง์ ๊ฐ์ง๋ค.
์์ ์ด์ง ํธ๋ฆฌ(Complete Binary Tree)
๋ง์ง๋ง ๋ ๋ฒจ์ ์ ์ธํ๋ฉด ๋ชจ๋ ๋
ธ๋๊ฐ ์ผ์ชฝ๋ถํฐ ์ฑ์์ ธ ์์ด์ผ ํจ.
์ฆ, ๋ฐฐ์ด(Array)๋ก ํํํ๊ธฐ ์ฌ์.
Heap Property(ํ ์์ฑ)
์ต์ ํ(Min-Heap) : ๋ถ๋ชจ ๋
ธ๋ โค ์์ ๋
ธ๋ โ ์ต์๊ฐ์ด ๋ฃจํธ(root)์ ์์น
์ต๋ ํ(Max-Heap) : ๋ถ๋ชจ ๋
ธ๋ โฅ ์์ ๋
ธ๋ โ ์ต๋๊ฐ์ด ๋ฃจํธ(root)์ ์์น
๋น ๋ฅธ ์ฝ์
/์ญ์ ์ฐ์ฐ
์ฝ์
(O(log N)) : ์๋ก์ด ๋
ธ๋๋ฅผ ์ถ๊ฐํ ํ Heapify Up(ํ ์ํฅ) ์ํ.
์ญ์ (O(log N)) : ๋ฃจํธ ๋
ธ๋๋ฅผ ์ ๊ฑฐํ ํ Heapify Down(ํ ํํฅ) ์ํ.
1
/ \
3 5
/ \ /
7 9 6
poll()์ ํ๋ฉด 1์ด ์ ๊ฑฐ๋๊ณ , ๋ค์ ์ต์๊ฐ(3)์ด ๋ฃจํธ๋ก ์ฌ๋ผ์ด.
9
/ \
7 6
/ \ /
3 5 1
poll()์ ํ๋ฉด 9๊ฐ ์ ๊ฑฐ๋๊ณ , ๋ค์ ์ต๋๊ฐ(7)์ด ๋ฃจํธ๋ก ์ฌ๋ผ์ด.
import java.util.PriorityQueue;
public class MinHeapExample {
public static void main(String[] args) {
PriorityQueue<Integer> minHeap = new PriorityQueue<>();
minHeap.add(5);
minHeap.add(1);
minHeap.add(8);
minHeap.add(3);
System.out.println(minHeap.poll()); // 1
System.out.println(minHeap.poll()); // 3
System.out.println(minHeap.poll()); // 5
System.out.println(minHeap.poll()); // 8
}
}
import java.util.PriorityQueue;
import java.util.Collections;
public class MaxHeapExample {
public static void main(String[] args) {
PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Collections.reverseOrder());
maxHeap.add(5);
maxHeap.add(1);
maxHeap.add(8);
maxHeap.add(3);
System.out.println(maxHeap.poll()); // 8
System.out.println(maxHeap.poll()); // 5
System.out.println(maxHeap.poll()); // 3
System.out.println(maxHeap.poll()); // 1
}
}