Created
May 30, 2018 06:38
-
-
Save sudhanshuptl/c04843f016dfadf1a4d8372d7ba8e63a to your computer and use it in GitHub Desktop.
Array based Max Heap implementation in Python
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
__author__ == 'Sudhanshu Patel' | |
''' | |
1. Height should be h or h-1 | |
2. max heap : parent node have hire value than all of its children | |
''' | |
class Heap_Array(object): | |
# Array Implementation of max Heap | |
# parent of a node is (i-1)/2 and child of a node is 2*i+1 and 2*i+2 | |
heap_type = 'MaxHeap' | |
def __init__(self, capacity=20): | |
self.arr = [None for x in range(capacity)] | |
self.count = 0 | |
self.capacity = capacity | |
def parent_node(self, i): | |
if i < 0 or i > self.count: | |
return False | |
return int((i-1)/2) | |
def left_child(self, i): | |
left = 2*i+1 | |
return False if left >= self.count else left | |
def right_child(self, i): | |
right = 2*i+2 | |
return False if right >= self.count else right | |
def insert(self, key): | |
#count have number of element in array | |
# so index of last element in heap is count-1 | |
if self.count < self.capacity: | |
self.arr[self.count] = key | |
self.heapify_up(self.count) | |
self.count += 1 | |
def print_heap(self): | |
print(', '.join([str(x) for x in self.arr[:self.count]])) | |
def heapify_down(self, parent): | |
''' | |
:param parent: | |
heapy parant node from top to bottom | |
''' | |
left = self.left_child(parent) | |
right = self.right_child(parent) | |
if left and self.arr[left] > self.arr[parent]: | |
max_ = left | |
else: | |
max_ = parent | |
if right and self.arr[right] > self.arr[max_]: | |
max_ = right | |
if max_ != parent: | |
#swap max index with parent | |
self.arr[parent], self.arr[max_] = self.arr[max_], self.arr[parent] | |
#recursive heapify | |
self.heapify_down(max_) | |
def heapify_up(self, child): | |
parent = self.parent_node(child) | |
if self.arr[parent] < self.arr[child]: | |
#swap | |
self.arr[parent], self.arr[child] = self.arr[child], self.arr[parent] | |
self.heapify_up(parent) | |
def drop_max(self): | |
''' | |
this is a max heap so root node is max, drop it replace it with last node. | |
delete lst node then heapify top to bottom | |
:return: max element of heap | |
''' | |
if self.count ==0 : | |
print('__ Heap is Empty !__') | |
return | |
max_data = self.arr[0] | |
self.arr[0] = self.arr[self.count-1] | |
self.arr[self.count-1] = None | |
self.count -= 1 | |
self.heapify_down(0) | |
return max_data | |
if __name__ == '__main__': | |
heap_arr = Heap_Array() | |
for i in range(1,10): | |
heap_arr.insert(i) | |
heap_arr.print_heap() | |
print('Drop Max :', heap_arr.drop_max()) | |
heap_arr.print_heap() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment