Created
December 29, 2018 20:41
-
-
Save ehborisov/cdd84650fd4463abe5afd64772821e20 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class MinHeap(object): | |
def __init__(self): | |
self.storage = [] | |
def add(self, val): | |
self.storage.append(val) | |
self._percolate_up() | |
def get_min(self): | |
if not self.storage: | |
return None | |
if len(self.storage) == 1: | |
return self.storage.pop() | |
m = self.storage[0] | |
self.storage[0] = self.storage.pop() | |
self._sift_down() | |
return m | |
def _swap(self, i, j): | |
self.storage[i] += self.storage[j] | |
self.storage[j] = self.storage[i] - self.storage[j] | |
self.storage[i] = self.storage[i] - self.storage[j] | |
def _percolate_up(self): | |
if not self.storage: | |
return | |
i = len(self.storage) - 1 | |
while i != 0: | |
parent = (i - 1) // 2 | |
if self.storage[parent] > self.storage[i]: | |
self._swap(parent, i) | |
i = parent | |
def _sift_down(self): | |
i = 0 | |
while True: | |
left_child = 2 * i + 1 | |
right_child = 2 * i + 2 | |
storage_len = len(self.storage) - 1 | |
if left_child > storage_len: | |
return | |
smallest = (left_child if right_child > storage_len or | |
self.storage[left_child] <= self.storage[right_child] else right_child) | |
if self.storage[i] > self.storage[smallest]: | |
self._swap(i, smallest) | |
i = smallest |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment