Created
November 8, 2016 03:35
-
-
Save jasonrdsouza/ffa82b5a012a85e771b37769bc6e836a to your computer and use it in GitHub Desktop.
Simple Heap Implementation
This file contains hidden or 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 Heap: | |
def __init__(self): | |
self.data = [] | |
self.length = 0 | |
def push(self, val): | |
if len(self.data) <= self.length: # need to expand the array | |
self.data.append(val) | |
else: | |
self.data[self.length] = val | |
self.length += 1 | |
self.heap_up() | |
def pop(self): | |
if self.length > 0: | |
top_val = self.data[0] | |
self.data[0] = self.data[self.length-1] | |
self.length -= 1 | |
self.heap_down() | |
return top_val | |
def parent_idx(self, child_idx): | |
return int((child_idx - 1) / 2) | |
def left_child_idx(self, parent_idx): | |
idx = int(parent_idx * 2 + 1) | |
if idx < self.length: | |
return idx | |
def right_child_idx(self, parent_idx): | |
idx = int(parent_idx * 2 + 2) | |
if idx < self.length: | |
return idx | |
def swap(self, idx1, idx2): | |
self.data[idx1], self.data[idx2] = self.data[idx2], self.data[idx1] | |
def heap_up(self): | |
curr_idx = self.length - 1 | |
while curr_idx > 0 and self.data[curr_idx] < self.data[self.parent_idx(curr_idx)]: | |
self.swap(curr_idx, self.parent_idx(curr_idx)) | |
curr_idx = self.parent_idx(curr_idx) | |
def min_child_idx(self, curr_idx): | |
left_idx = self.left_child_idx(curr_idx) | |
right_idx = self.right_child_idx(curr_idx) | |
if left_idx and right_idx: # both children exist, so choose the smaller one | |
return left_idx if self.data[left_idx] < self.data[right_idx] else right_idx | |
elif left_idx: | |
return left_idx | |
elif right_idx: | |
return right_idx | |
else: | |
return None | |
def heap_down(self): | |
curr_idx = 0 | |
min_idx = self.min_child_idx(curr_idx) | |
while curr_idx < self.length and min_idx and self.data[curr_idx] > self.data[min_idx]: | |
self.swap(curr_idx, min_idx) | |
curr_idx = min_idx | |
min_idx = self.min_child_idx(curr_idx) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment