From e15c0aacc96f701348d4a328ba93e450de345a5b Mon Sep 17 00:00:00 2001 From: Ankit Agarwal Date: Sat, 1 Apr 2017 21:16:11 +0530 Subject: [PATCH 1/2] Contributing code for Heap data structure, and all basic operations associated with it. --- data_structures/Heap/heap.py | 84 ++++++++++++++++++++++++++++++++++++ 1 file changed, 84 insertions(+) create mode 100644 data_structures/Heap/heap.py diff --git a/data_structures/Heap/heap.py b/data_structures/Heap/heap.py new file mode 100644 index 000000000000..3b22f4f02083 --- /dev/null +++ b/data_structures/Heap/heap.py @@ -0,0 +1,84 @@ +#!/usr/bin/python + +class Heap: + def __init__(self): + self.h = [] + self.currsize = 0 + + def leftChild(self,i): + if 2*i+1 < self.currsize: + return 2*i+1 + return None + + def rightChild(self,i): + if 2*i+2 < self.currsize: + return 2*i+2 + return None + + def maxHeapify(self,node): + if node < self.currsize: + m = node + lc = self.leftChild(node) + rc = self.rightChild(node) + if lc is not None and self.h[lc] > self.h[m]: + m = lc + if rc is not None and self.h[rc] > self.h[m]: + m = rc + if m!=node: + temp = self.h[node] + self.h[node] = self.h[m] + self.h[m] = temp + self.maxHeapify(m) + + def buildHeap(self,a): + self.currsize = len(a) + self.h = list(a) + for i in range(self.currsize/2,-1,-1): + self.maxHeapify(i) + + def getMax(self): + if self.currsize >= 1: + me = self.h[0] + temp = self.h[0] + self.h[0] = self.h[self.currsize-1] + self.h[self.currsize-1] = temp + self.currsize -= 1 + self.maxHeapify(0) + return me + return None + + def heapSort(self): + size = self.currsize + while self.currsize-1 >= 0: + temp = self.h[0] + self.h[0] = self.h[self.currsize-1] + self.h[self.currsize-1] = temp + self.currsize -= 1 + self.maxHeapify(0) + self.currsize = size + + def insert(self,data): + self.h.append(data) + curr = self.currsize + self.currsize+=1 + while self.h[curr] > self.h[curr/2]: + temp = self.h[curr/2] + self.h[curr/2] = self.h[curr] + self.h[curr] = temp + curr = curr/2 + + def display(self): + for item in self.h: + print item, + +def main(): + l = list(map(int,raw_input().split())) + h = Heap() + h.buildHeap(l) + h.heapSort() + h.display() + +if __name__=='__main__': + main() + + From fa1e65ee0fc6220c17712fa135b3d81bc54deadd Mon Sep 17 00:00:00 2001 From: Ankit Agarwal Date: Sat, 1 Apr 2017 21:28:12 +0530 Subject: [PATCH 2/2] Fixing print statement --- data_structures/Heap/heap.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/data_structures/Heap/heap.py b/data_structures/Heap/heap.py index 3b22f4f02083..d43cc4baa177 100644 --- a/data_structures/Heap/heap.py +++ b/data_structures/Heap/heap.py @@ -68,8 +68,7 @@ def insert(self,data): curr = curr/2 def display(self): - for item in self.h: - print item, + print (self.h) def main(): l = list(map(int,raw_input().split()))