|
| 1 | + |
| 2 | +class BinaryHeap: |
| 3 | + def __init__(self): |
| 4 | + self.pointer: int = 0 |
| 5 | + self.heap: list = [None] |
| 6 | + |
| 7 | + def is_empty(self) -> bool: |
| 8 | + return self.pointer == 0 |
| 9 | + |
| 10 | + def insert(self, item): |
| 11 | + self.heap.append(item) |
| 12 | + self.pointer += 1 |
| 13 | + self.perc_up(self.pointer) |
| 14 | + |
| 15 | + def perc_up(self, index: int): |
| 16 | + while index // 2 > 0: |
| 17 | + if self.heap[index] < self.heap[index // 2]: |
| 18 | + self.heap[index], self.heap[index // 2] = self.heap[index // 2], self.heap[index] |
| 19 | + index = index // 2 |
| 20 | + |
| 21 | + def get_min(self): |
| 22 | + if self.is_empty(): |
| 23 | + raise Exception("Heap is empty") |
| 24 | + return self.heap[1] |
| 25 | + |
| 26 | + def delete_min(self): |
| 27 | + if self.is_empty(): |
| 28 | + raise Exception("Heap is empty") |
| 29 | + ret_value: int = self.heap[1] |
| 30 | + self.heap[1] = self.heap[self.pointer] |
| 31 | + self.heap.pop() |
| 32 | + self.pointer -= 1 |
| 33 | + self.perc_down(1) |
| 34 | + return ret_value |
| 35 | + |
| 36 | + def perc_down(self, index: int): |
| 37 | + while index * 2 <= self.pointer: |
| 38 | + swap_index: int = self.find_swap_index(index) |
| 39 | + if self.heap[swap_index] < self.heap[index]: |
| 40 | + self.heap[swap_index], self.heap[index] = self.heap[index], self.heap[swap_index] |
| 41 | + index = swap_index |
| 42 | + |
| 43 | + def find_swap_index(self, index: int) -> int: |
| 44 | + if index * 2 + 1 > self.pointer: |
| 45 | + return index * 2 |
| 46 | + else: |
| 47 | + if self.heap[index * 2] <= self.heap[index * 2 + 1]: |
| 48 | + return index * 2 |
| 49 | + else: |
| 50 | + return index * 2 + 1 |
| 51 | + |
| 52 | + def build_heap(self, nums: list): |
| 53 | + for n in nums: |
| 54 | + self.insert(n) |
| 55 | + |
| 56 | + |
| 57 | +h: BinaryHeap = BinaryHeap() |
| 58 | +h.insert(10) |
| 59 | +h.insert(1) |
| 60 | +h.insert(3) |
| 61 | +print(h.heap) # [None, 1, 10, 3] |
| 62 | +print(h.get_min()) # 1 |
| 63 | + |
| 64 | +while not h.is_empty(): |
| 65 | + print(h.delete_min()) |
0 commit comments