■ 이진 힙(Binary Heap)을 구현하는 방법을 보여준다. (최소 힙)
▶ 예제 코드 (PY)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 |
class BinaryHeap: def __init__(self): self.heap = [] def push(self, value): self.heap.append(value) self.bubbleUp(len(self.heap) - 1) def pop(self): if len(self.heap) == 0: return None minimumValue = self.heap[0] self.heap[0] = self.heap[-1] self.heap.pop() self.bubbleDown(0) return minimumValue def bubbleUp(self, index): parentIndex = (index - 1) // 2 while index > 0 and self.heap[parentIndex] > self.heap[index]: self.heap[parentIndex], self.heap[index] = self.heap[index], self.heap[parentIndex] index = parentIndex parentIndex = (index - 1) // 2 def bubbleDown(self, index): heapLength = len(self.heap) while True: leftChildIndex = 2 * index + 1 rightChildIndex = 2 * index + 2 smallestIndex = index if leftChildIndex < heapLength and self.heap[leftChildIndex] < self.heap[smallestIndex]: smallestIndex = leftChildIndex if rightChildIndex < heapLength and self.heap[rightChildIndex] < self.heap[smallestIndex]: smallestIndex = rightChildIndex if smallestIndex == index: break self.heap[index], self.heap[smallestIndex] = self.heap[smallestIndex], self.heap[index] index = smallestIndex binaryHeap = BinaryHeap() binaryHeap.push(10) binaryHeap.push(5) binaryHeap.push(55) binaryHeap.push(30) binaryHeap.push(100) print(binaryHeap.heap) print() print(binaryHeap.pop()) print(binaryHeap.pop()) print(binaryHeap.pop()) print() print(binaryHeap.heap) print() """ [5, 10, 55, 30, 100] 5 10 30 [55, 100] """ |