ํ๊ณผ ๋ฐฐ์ด
- ์ผ๋ฐ์ ์ผ๋ก ํ ๊ตฌํ ์, ๋ฐฐ์ด ์๋ฃ๊ตฌ์กฐ ํ์ฉ
- ๋ฐฐ์ด์ ์ธ๋ฑ์ค 0 ๋ถํฐ ์์ํ์ง๋ง, ํ ๊ตฌํ์ ํธ์๋ฅผ ์ํด root ๋
ธ๋ ์ธ๋ฑ์ค ๋ฒํธ๋ฅผ 1๋ก ์ง์
- ๋ถ๋ชจ ๋
ธ๋ ์ธ๋ฑ์ค(parent node's index) = ์์ ๋
ธ๋ ์ธ๋ฑ์ค(child node's index) //2
- ์ผ์ชฝ ์์ ๋
ธ๋ ์ธ๋ฑ์ค(left child node's index) = ๋ถ๋ชจ ๋
ธ๋ ์ธ๋ฑ์ค(parent node's index) * 2
- ์ค๋ฅธ์ชฝ ์์ ๋
ธ๋ ์ธ๋ฑ์ค(right child node's index) = ๋ถ๋ชจ ๋
ธ๋ ์ธ๋ฑ์ค(parent node's index) * 2 + 1
Heap ๊ณผ ์ธ๋ฑ์ค ๋ฒํธ
ํ๊ณผ ๋ฐ์ดํฐ ์ฝ์
(Max Heap)
class Heap:
def __init__(self, data):
self.heap_array = list()
self.heap_array.append(None)
self.heap_array.append(data)
heap = Heap(1)
heap.heap_array #[None, 1]
def insert(self, data):
if len(self.heap_array) == 0:
self.heap_array.append(None)
self.heap_array.append(data)
return True
self.heap_array.append(data)
return True
- insert() ๋ณํ : ์ฝ์
ํ ๋
ธ๋๊ฐ ๋ถ๋ชจ ๋
ธ๋๊ฐ๋ณด๋ค ํด ๊ฒฝ์ฐ, ๋ถ๋ชจ ๋
ธ๋์ ์ฝ์
๋
ธ๋ ์์น ๋ณ๊ฒฝ
def move_up(self, inserted_idx):
if inserted_idx <= 1:
return False
parent_idx = inserted_idx // 2
if self.heap_array[inserted_idx] > self.heap_array[parent_idx]:
return True
else:
return False
def insert(self, data):
if len(self.heap_array) == 0:
self.heap_array.append(None)
self.heap_array.append(data)
return True
self.heap_array.append(data)
inserted_idx = len(self.heap_array) - 1
while self.move_up(inserted_idx):
parent_idx = inserted_idx // 2
self.heap_array[inserted_idx], self.heap_array[parent_idx] = self.heap_array[parent_idx], self.heap_array[inserted_idx]
inserted_idx = parent_idx
return True
ํ์ ๋ฐ์ดํฐ ์ญ์ (Max Heap)
- ๋ณดํต ์ญ์ ๋ ์ต์๋จ ๋
ธ๋(root node)๋ฅผ ์ญ์ ํ๋ ๊ฒ์ด ์ผ๋ฐ์
- (cf. ํ์ ์ฉ๋๋ ์ต๋๊ฐ ๋๋ ์ต์๊ฐ์ root node์ ๋์์, ๋น ๋ฅด๊ฒ ๊บผ๋ด์ฐ๋๋ก ํ๋ ๊ฒ)
class Heap:
def __init__(self, data):
self.heap_array = list()
self.heap_array.append(None)
self.heap_array.append(data)
def pop(self):
if len(self.heap_array) <= 1:
return None
returned_data = self.heap_array[1]
return returned_data
ํ(Heap) ์๊ฐ ๋ณต์ก๋
- depth(ํธ๋ฆฌ์ ๋์ด)๋ฅผ h๋ผ๊ณ ํ๊ธฐ
- n๊ฐ์ ๋
ธ๋๋ฅผ ๊ฐ์ง๋ heap์ ๋ฐ์ดํฐ ์ฝ์
๋๋ ์ญ์ ์, ์ต์
์ ๊ฒฝ์ฐ root ๋
ธ๋์์ leaf ๋
ธ๋๊น์ง ๋น๊ตํด์ผ ํ๋ฏ๋ก ์๊ฐ ๋ณต์ก๋๋ O(logn)
- ์ฐธ๊ณ : ๋น
์ค ํ๊ธฐ๋ฒ์์ logn ์์ log์ ๋ฐ์ 2
- ํ๋ฒ ์คํ ์, 50%์ ์คํํ ์๋ ์๋ ๋ช
๋ น์ ์ ๊ฑฐํ๋ค๋ ์๋ฏธ => 50%์ ์คํ์๊ฐ์ ๋จ์ถ์ํฌ ์ ์๋ค!