-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathminHeap.py
More file actions
60 lines (47 loc) · 1.71 KB
/
Copy pathminHeap.py
File metadata and controls
60 lines (47 loc) · 1.71 KB
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 MinHeap:
def __init__(self, array):
self.heap = self.buildHeap(array)
def buildHeap(self, array):
firstParentId = (len(array) - 2) // 2
for currentId in reversed(range(firstParentId + 1)):
self.siftDown(currentId, len(array) - 1, array)
return array
def siftDown(self, currentId, endId, heap):
childOne = currentId*2 + 1
while(childOne <= endId):
childTwo = currentId*2 + 2 if (currentId*2 + 2) < endId else -1
if (childTwo != -1 and heap[childTwo] < heap[childOne]):
idToSwap = childTwo
else:
idToSwap = childOne
if(heap[idToSwap] < heap[currentId]):
self.swap(idToSwap, currentId, heap)
currentId = idToSwap
childOne = currentId*2 + 1
else:
return
def siftUp(self, currentId, heap):
parentId = (currentId - 1)//2
while(currentId > 0 and heap[currentId] < heap[parentId]):
self.swap(parentId, currentId, heap)
currentId = parentId
parentId = (currentId - 1)//2
def peek(self):
return self.heap[0]
def remove(self):
self.swap(0, len(self.heap) - 1, self.heap)
valueToRemove = self.heap.pop()
self.siftDown(0, len(self.heap)-1, self.heap)
return valueToRemove
def insert(self, value):
self.heap.append(value)
self.siftUp(len(self.heap)-1, self.heap)
def swap(self, i, j, heap):
heap[i], heap[j] = heap[j], heap[i]
def display(self):
return self.heap
def test():
a = MinHeap([2,3,1,4])
assert a.display() == [1,3,2,4]
print("Passed")
test()