|
| 1 | +class BinaryHeap: |
| 2 | + """ |
| 3 | + A max-heap implementation in Python |
| 4 | + >>> binary_heap = BinaryHeap() |
| 5 | + >>> binary_heap.insert(6) |
| 6 | + >>> binary_heap.insert(10) |
| 7 | + >>> binary_heap.insert(15) |
| 8 | + >>> binary_heap.insert(12) |
| 9 | + >>> binary_heap.pop() |
| 10 | + 15 |
| 11 | + >>> binary_heap.pop() |
| 12 | + 12 |
| 13 | + >>> binary_heap.get_list |
| 14 | + [10, 6] |
| 15 | + >>> len(binary_heap) |
| 16 | + 2 |
| 17 | + """ |
| 18 | + |
| 19 | + def __init__(self): |
| 20 | + self.__heap = [0] |
| 21 | + self.__size = 0 |
| 22 | + |
| 23 | + def __swap_up(self, i: int) -> None: |
| 24 | + """ Swap the element up """ |
| 25 | + temporary = self.__heap[i] |
| 26 | + while i // 2 > 0: |
| 27 | + if self.__heap[i] > self.__heap[i // 2]: |
| 28 | + self.__heap[i] = self.__heap[i // 2] |
| 29 | + self.__heap[i // 2] = temporary |
| 30 | + i //= 2 |
| 31 | + |
| 32 | + def insert(self, value: int) -> None: |
| 33 | + """ Insert new element """ |
| 34 | + self.__heap.append(value) |
| 35 | + self.__size += 1 |
| 36 | + self.__swap_up(self.__size) |
| 37 | + |
| 38 | + def __swap_down(self, i: int) -> None: |
| 39 | + """ Swap the element down """ |
| 40 | + while self.__size >= 2 * i: |
| 41 | + if 2 * i + 1 > self.__size: |
| 42 | + bigger_child = 2 * i |
| 43 | + else: |
| 44 | + if self.__heap[2 * i] > self.__heap[2 * i + 1]: |
| 45 | + bigger_child = 2 * i |
| 46 | + else: |
| 47 | + bigger_child = 2 * i + 1 |
| 48 | + temporary = self.__heap[i] |
| 49 | + if self.__heap[i] < self.__heap[bigger_child]: |
| 50 | + self.__heap[i] = self.__heap[bigger_child] |
| 51 | + self.__heap[bigger_child] = temporary |
| 52 | + i = bigger_child |
| 53 | + |
| 54 | + def pop(self) -> int: |
| 55 | + """ Pop the root element """ |
| 56 | + max_value = self.__heap[1] |
| 57 | + self.__heap[1] = self.__heap[self.__size] |
| 58 | + self.__size -= 1 |
| 59 | + self.__heap.pop() |
| 60 | + self.__swap_down(1) |
| 61 | + return max_value |
| 62 | + |
| 63 | + @property |
| 64 | + def get_list(self): |
| 65 | + return self.__heap[1:] |
| 66 | + |
| 67 | + def __len__(self): |
| 68 | + """ Length of the array """ |
| 69 | + return self.__size |
| 70 | + |
| 71 | + |
| 72 | +if __name__ == "__main__": |
| 73 | + import doctest |
| 74 | + |
| 75 | + doctest.testmod() |
| 76 | + # create an instance of BinaryHeap |
| 77 | + binary_heap = BinaryHeap() |
| 78 | + binary_heap.insert(6) |
| 79 | + binary_heap.insert(10) |
| 80 | + binary_heap.insert(15) |
| 81 | + binary_heap.insert(12) |
| 82 | + # pop root(max-values because it is max heap) |
| 83 | + print(binary_heap.pop()) # 15 |
| 84 | + print(binary_heap.pop()) # 12 |
| 85 | + # get the list and size after operations |
| 86 | + print(binary_heap.get_list) |
| 87 | + print(len(binary_heap)) |
0 commit comments