Skip to content

Instantly share code, notes, and snippets.

@cyyeh
Created September 6, 2018 04:56
Show Gist options
  • Save cyyeh/47f980577faaa595fa142b26397caf79 to your computer and use it in GitHub Desktop.
Save cyyeh/47f980577faaa595fa142b26397caf79 to your computer and use it in GitHub Desktop.
max_binary_heap.py
class MaxBinaryHeap:
def __init__(self, values=[]):
self.values = values
self.build_max_heap()
def max(self):
"""return first element in the array"""
if len(self.values) > 0:
return self.value[0]
else:
return None
def heap_size(self):
return len(self.values)
def build_max_heap(self):
for i in range(self.heap_size() // 2, 0, -1):
self.max_heapify(i - 1)
def max_heapify(self, i):
l = self.left(i)
r = self.right(i)
if l <= (self.heap_size() - 1) and self.values[l] > self.values[i]:
largest = l
else:
largest = i
if r <= self.heap_size() and self.values[r] > self.values[largest]:
largest = r
if largest != i:
self.values[i], self.values[largest] = self.values[largest], self.values[i]
self.max_heapify(largest)
def parent(self, node_index):
"""returns index of node's parent"""
return node_index // 2
def left(self, node_index):
"""returns index of node's left child"""
return node_index * 2
def right(self, node_index):
"""returns index of node's right child"""
return 2 * node_index + 1
def print_as_list(self):
"""print heap in list form"""
print(self.values)
def print_as_tree(self, indent = 0):
"""print heap in tree form"""
heap = MaxBinaryHeap([4, 1, 3, 2, 16, 9, 10, 14, 8, 7])
heap.print_as_list()
#heap.print_as_tree()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment