-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathheap.py
60 lines (60 loc) · 1.83 KB
/
heap.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
class Heap:
def __init__(self):
self.heapList = list()
self.size = 0
#indexing the nodes
def leftChild(self, i):
return 2*i+1
def rightChild(self, i):
return 2*i+2
def parent(self, i):
return i//2
# Getting MAX in MaxHeap and MIN Values in MinHeap
def getMax(self):# for MaxHeap: O(1)
if self.size > 0:
return self.heapList[0]
else:raise Exception("Empty Heap")
def getMin(self): # for MinHeap: O(1)
if self.size > 0:
return self.heapList[0]
else:raise Exception("Empty Heap")
#Heapifying the complete Binary tree
def percolateDown(self, i):
while (i*2)<= self.size:
minimumChild = self.minChild(i)
if self.heapList[i]>self.heapList[minimumChild]:
self.heapList[i],self.heapList[minimumChild]=self.heapList[minimumChild],self.heapList[i]
i=minimumChild
def minChild(self, i):
if i*2+1 > self.size:
return i*2
else:
if self.heapList[i*2] < self.heapList[i*2+1]:
return i*2
else:
return i*2+1
def percolateUp(self, i):
while i//2>0:
if self.heapList[i]<self.heapList[i//2]:
self.heapList[i],self.heapList[i//2]=self.heapList[i//2],self.heapList[i]
i=i//2
# Inserting the elements
def insert(self, val):
self.heapList.append(val)
self.size+=1
self.percolateUp(self.size-1)
# Deleting the elements
def delete(self):
pass
def printHeap(self):
for ele in self.heapList:
print(ele,end=" ")
hp=Heap()
hp.insert(10)
hp.insert(20)
hp.insert(30)
hp.insert(40)
hp.insert(50)
hp.insert(60)
hp.insert(70)
hp.printHeap()