MCPcopy
hub / github.com/keon/algorithms / BinaryHeap

Class BinaryHeap

algorithms/data_structures/heap.py:70–151  ·  view source on GitHub ↗

Min binary heap using array representation. Examples: >>> heap = BinaryHeap() >>> heap.insert(5) >>> heap.insert(3) >>> heap.remove_min() 3

Source from the content-addressed store, hash-verified

68
69
70class BinaryHeap(AbstractHeap):
71 """Min binary heap using array representation.
72
73 Examples:
74 >>> heap = BinaryHeap()
75 >>> heap.insert(5)
76 >>> heap.insert(3)
77 >>> heap.remove_min()
78 3
79 """
80
81 def __init__(self) -> None:
82 """Initialize the binary heap with a sentinel at index 0."""
83 self.current_size: int = 0
84 self.heap: list[int] = [0]
85
86 def perc_up(self, index: int) -> None:
87 """Percolate element up to maintain the min-heap invariant.
88
89 Args:
90 index: Index of the element to percolate up.
91 """
92 while index // 2 > 0:
93 if self.heap[index] < self.heap[index // 2]:
94 self.heap[index], self.heap[index // 2] = (
95 self.heap[index // 2],
96 self.heap[index],
97 )
98 index = index // 2
99
100 def insert(self, val: int) -> None:
101 """Insert a value into the heap.
102
103 Args:
104 val: The value to insert.
105 """
106 self.heap.append(val)
107 self.current_size = self.current_size + 1
108 self.perc_up(self.current_size)
109
110 def min_child(self, index: int) -> int:
111 """Return the index of the smaller child of a parent node.
112
113 Args:
114 index: Index of the parent node.
115
116 Returns:
117 Index of the smaller child.
118 """
119 if 2 * index + 1 > self.current_size:
120 return 2 * index
121 if self.heap[2 * index] > self.heap[2 * index + 1]:
122 return 2 * index + 1
123 return 2 * index
124
125 def perc_down(self, index: int) -> None:
126 """Percolate element down to maintain the min-heap invariant.
127

Callers 1

setUpMethod · 0.90

Calls

no outgoing calls

Tested by 1

setUpMethod · 0.72