Created
January 8, 2017 06:42
-
-
Save drem-darios/ad74d12bb49d5c63e42d291229b7f2e6 to your computer and use it in GitHub Desktop.
Example of a max heap implementation
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 MaxHeap(object): | |
heap_values = None | |
def __init__(self): | |
self.heap_values = [] | |
def get_max(self): | |
return self.heap_values[0] | |
def insert(self, insert_me): | |
self.heap_values.append(insert_me) # Insert at end of array | |
self._percolate_up(len(self.heap_values) - 1) # Percolate up to root if needed | |
def delete_max(self): | |
if len(self.heap_values) == 0: | |
return | |
self._swap(0, len(self.heap_values) - 1) | |
self.heap_values.pop(len(self.heap_values) - 1) # Delete last element | |
self._percolate_down(0) | |
def _get_left(self, parent): | |
index = (2 * parent) + 1 | |
if index >= len(self.heap_values): | |
return -1 | |
return self.heap_values[index] | |
def _get_right(self, parent): | |
index = (2 * parent) + 2 | |
if index >= len(self.heap_values): | |
return -1 | |
return self.heap_values[index] | |
def _get_parent(self, index): | |
parent = (index - 1) / 2 | |
return self.heap_values[parent] | |
def _percolate_down(self, current_index): | |
if len(self.heap_values) == 0: | |
return | |
node = self.heap_values[current_index] | |
left = self._get_left(current_index) | |
right = self._get_right(current_index) | |
if left > right: | |
if left > node: | |
self._swap(current_index, (2 * current_index) + 1) | |
self._percolate_down((2 * current_index) + 1) | |
elif right > left: | |
if right > node: | |
self._swap(current_index, (2 * current_index) + 2) | |
self._percolate_down((2 * current_index) + 2) | |
def _percolate_up(self, current_index): | |
if current_index == 0: | |
return -1 | |
node = self.heap_values[current_index] | |
parent = self._get_parent(current_index) | |
if node > parent: | |
self._swap(current_index, (current_index - 1) / 2) | |
self._percolate_up((current_index - 1) / 2) | |
def _swap(self, first, second): | |
temp = self.heap_values[first] | |
self.heap_values[first] = self.heap_values[second] | |
self.heap_values[second] = temp | |
def main(): | |
x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19] | |
y = MaxHeap() | |
for val in x: | |
y.insert(val) | |
print y.heap_values | |
for i in range(len(y.heap_values)): | |
y.delete_max() | |
print y.heap_values | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment