์ฐ์ ์์ ํ๋?
์ฐ์ ์์์ ๊ฐ๋ ์ ํ์ ๋์ ํ ์๋ฃ ๊ตฌ์กฐ
๋ฐ์ดํฐ๋ค์ด ์ฐ์ ์์๋ฅผ ๊ฐ์ง๊ณ ์๊ณ ์ฐ์ ์์๊ฐ ๋์ ๋ฐ์ดํฐ๊ฐ ๋จผ์ ๋๊ฐ๋ค.
์ฐ์ ์์ ํ๋ ๋ฐฐ์ด, ์ฐ๊ฒฐ๋ฆฌ์คํธ, ํ ์ผ๋ก ๊ตฌํ์ด ๊ฐ๋ฅํ๋ค. ์ด ์ค์์ ํ(heap)์ผ๋ก ๊ตฌํํ๋ ๊ฒ์ด ๊ฐ์ฅ ํจ์จ์ ์ด๋ค.
ํ์ด๋?
์์ ์ด์งํธ๋ฆฌ ๊ตฌ์กฐ
์ต๋๊ฐ๊ณผ ์ต์๊ฐ์ ๋ฝ์๋ผ ๋ ์ฌ์ฉํ๊ธฐ ์ข์ ์๋ฃ๊ตฌ์กฐ์ด๋ค.
ํ์ ์์ ํ ์ ๋ ฌ๋ ์ํ๋ฅผ ์ ์งํ๋ ๊ฒ์ด ์๋ Level์ ๋ฐ๋ฅธ ์ ๋ ฌ๋ง ์ด๋ฃจ์ด์ ธ ๋์จํ ์ ๋ ฌ์ํ๋ฅผ ์ ์งํ๋ค.
(Max Heap์ธ ๊ฒฝ์ฐ ๋ถ๋ชจ๊ฐ ์์๋ณด๋ค ํฐ ๊ฐ์ ๊ฐ์ง๊ณ ์๊ณ , Min Heap์ธ ๊ฒฝ์ฐ ๋ถ๋ชจ๊ฐ ์์๋ณด๋ค ์์ ๊ฐ์ ๊ฐ์ง๊ณ ์์ด์ผ ํจ)
ํ์ ์ข ๋ฅ
Max Heap
- ๋ฃจํธ ๋ ธ๋์๋ ํญ์ ๊ฐ์ฅ ํฐ ๊ฐ์ด ์์นํ๊ณ ์์ผ๋ฉฐ, ๋ถ๋ชจ ๋ ธ๋๊ฐ ์์ ๋ ธ๋๋ค๋ณด๋ค ๋ฌด์กฐ๊ฑด ๊ฐ์ด ์ปค์ผํ๋ค.
Min Heap
- ๋ฃจํธ ๋ ธ๋์๋ ํญ์ ๊ฐ์ฅ ์์ ๊ฐ์ด ์์นํ๊ณ ์์ผ๋ฉฐ, ๋ถ๋ชจ ๋ ธ๋๊ฐ ์์ ๋ ธ๋๋ค๋ณด๋ค ๋ฌด์กฐ๊ฑด ๊ฐ์ด ์์์ผํ๋ค.
ํ์ ๊ตฌํ
- ํ์ ๋ณดํต ๋ฐฐ์ด์ ์ด์ฉํ์ฌ ๊ตฌํํ๋ฉฐ, ๋ถ๋ชจ ๋ ธ๋์ ์์ ๋ ธ๋๋ฅผ ๊ตฌ๋ถํ๋ ๋ฐฉ์์ ๋ค์๊ณผ ๊ฐ๋ค.
- ๋ถ๋ชจ์ ์ธ๋ฑ์ค๋ฅผ i๋ผ๊ณ ํ์๋ ์ผ์ชฝ ์์์ ์ธ๋ฑ์ค๋ 2 * i, ์ค๋ฅธ์ชฝ ์์์ ์ธ๋ฑ์ค๋ 2 * i + 1 ์ด๋ค.
ํ์ ์ฝ์ ์ฐ์ฐ
- ๊ฐ์ฅ ๋ง์ง๋ง ์์น์ ์ฝ์ ํ ๋ฐ์ดํฐ๋ฅผ ์ฝ์ ํ๋ค.
- ํ์ ํน์ฑ์ ๋ง๊ฒ ๋ฐ์ดํฐ๋ค์ ์์น๋ฅผ ์กฐ์ ํ๋ค.
ํ์ ์ญ์ ์ฐ์ฐ
- ๋ฃจํธ ๋ ธ๋๋ฅผ ์ ๊ฑฐ ํ๋ค.
- ๋ง์ง๋ง ๋ ธ๋๋ฅผ ๋ฃจํธ ๋ ธ๋์ ์์น๋ก ์ฎ๊ธด๋ค.
- ํ์ ํน์ฑ์ ๋ง๊ฒ ๋ฐ์ดํฐ๋ค์ ์์น๋ฅผ ์กฐ์ ํ๋ค.
์๋ฐ๋ฅผ ์ด์ฉํ ๊ตฌํ
public void insert(int n) {
heap[++heapSize] = n;
int parent = heapSize/2;
int child = heapSize;
while(child >= 2 && heap[parent] < heap[child]) {
SWAP(parent, child);
child = parent;
parent = child/2;
}
}
public int delete() {
int data = heap[1];
heap[1] = heap[heapSize--];
int parent = 1;
int child = 2;
while(child <= heapSize && heap[parent] < heap[child]) {
SWAP(parent, child);
parent = child;
child = heap[heap[parent * 2] < heap[parent * 2 + 1] ? parent * 2 + 1 : parent * 2];
}
return data;
}
https://gmlwjd9405.github.io/2018/05/10/data-structure-heap.html
[์๋ฃ๊ตฌ์กฐ] ํ(heap)์ด๋ - Heee's Development Blog
Step by step goes a long way.
gmlwjd9405.github.io
์ฐ์ ์์ ํ ADT
์ด ๋ธ๋ก๊ทธ์ ๋ชจ๋ ์์ ์ฝ๋๋ ๊นํ๋ธ์์๋ ๋ณผ ์ ์์ต๋๋ค. ์๋์ ํฌ์คํธ๋ ๊ฐ์ธ์ ์ธ ์ฉ๋๋ก ๋ด์ฉ์ ์์ฝํ ๊ฒ ์ ๋๋ค. https://github.com/AeroCodeX/ ์ฐ์ ์์ ํ ADT ๋ฐ์ดํฐ์ ์ฐ์ ์์๊ฐ ์กด์ฌํ์ฌ,
aerocode.net