-
패스트 캠퍼스 챌린지 24일차 - 자료구조 힙#3카테고리 없음 2021. 9. 29. 19:34
목차
- Heap의 Insert
- Heap의 구현(Insert)
1.Heap의 Insert
- 일반적으로 힙 구현시 배열 자료구조를 활용함
- 배열은 인덱스가 0번부터 시작하지만, 힙 구현의 편의를 위해, root 노드 인덱스 번호를 1로 지정하면, 구현이 좀더 수월함
- 인덱스 번호는 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
2.Heap의 구현(Insert)
class Heap: def __init__(self, data): self.heap_array = list() self.heap_array.append(None) self.heap_array.append(data) 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