|
| 1 | +# Author: OMKAR PATHAK |
| 2 | + |
| 3 | +class BinaryHeap(object): |
| 4 | + def __init__(self): |
| 5 | + self.heap = [0] |
| 6 | + self.currentSize = 0 |
| 7 | + |
| 8 | + def __repr__(self): |
| 9 | + heap = self.heap[1:] |
| 10 | + return ' '.join(str(i) for i in heap) |
| 11 | + |
| 12 | + # for shifting the node up |
| 13 | + def shiftUp(self, index): |
| 14 | + while (index // 2) > 0: |
| 15 | + if self.heap[index] < self.heap[index // 2]: # (currentSize // 2) is the parent |
| 16 | + temp = self.heap[index // 2] |
| 17 | + self.heap[index // 2] = self.heap[index] |
| 18 | + self.heap[index] = temp |
| 19 | + index = index // 2 |
| 20 | + |
| 21 | + # to insert a node in the heap |
| 22 | + def insert(self, key): |
| 23 | + self.heap.append(key) |
| 24 | + self.currentSize += 1 |
| 25 | + self.shiftUp(self.currentSize) |
| 26 | + |
| 27 | + # for shifting down a node |
| 28 | + def shiftDown(self, index): |
| 29 | + while(index * 2) <= self.currentSize: |
| 30 | + minimumChild = self.minChild(index) |
| 31 | + if self.heap[index] > self.heap[minimumChild]: |
| 32 | + temp = self.heap[index] |
| 33 | + self.heap[index] = self.heap[minimumChild] |
| 34 | + self.heap[minimumChild] = temp |
| 35 | + index = minimumChild |
| 36 | + |
| 37 | + # for finding the child with minimum value |
| 38 | + def minChild(self,i): |
| 39 | + if i * 2 + 1 > self.currentSize: |
| 40 | + return i * 2 |
| 41 | + else: |
| 42 | + if self.heap[i * 2] < self.heap[i * 2 + 1]: |
| 43 | + return i * 2 |
| 44 | + else: |
| 45 | + return i * 2 + 1 |
| 46 | + |
| 47 | + # for deleting a node from the heap and maintaining the heap property |
| 48 | + def delete(self): |
| 49 | + deletedNode = self.heap[1] |
| 50 | + self.heap[1] = self.heap[self.currentSize] |
| 51 | + self.currentSize -= 1 |
| 52 | + self.heap.pop() |
| 53 | + self.shiftDown(1) |
| 54 | + return deletedNode |
| 55 | + |
| 56 | + # for building heap |
| 57 | + def buildHeap(self, alist): |
| 58 | + i = len(alist) // 2 |
| 59 | + self.currentSize = len(alist) |
| 60 | + self.heap = [0] + alist[:] |
| 61 | + while (i > 0): |
| 62 | + self.shiftDown(i) |
| 63 | + i = i - 1 |
| 64 | + |
| 65 | +bh = BinaryHeap() |
| 66 | +bh.buildHeap([9,5,6,2,3]) |
| 67 | + |
| 68 | +print('Deleted:', bh.delete()) |
| 69 | +print('Deleted:', bh.delete()) |
| 70 | +print('Deleted:', bh.delete()) |
| 71 | +bh.insert(3) |
| 72 | +print('Deleted:', bh.delete()) |
| 73 | +print(bh) |
0 commit comments