-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathHeap.py
63 lines (51 loc) · 1.97 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
61
def swap(array, i, j):
array[i], array[j] = array[j], array[i]
class Heap:
def __init__(self, array, callback):
self.heap = self.buildHeap(array)
self.callback = callback
self.length = len(self.heap)
def buildHeap(self, array):
firstParentIdx = (len(array)-2)//2
for currentIdx in reversed(range(firstParentIdx+1)):
self.siftDown(array, currentIdx, len(array)-1)
return array
def siftUp(self, heap, currentIdx):
parentIdx = (currentIdx-1)//2
while currentIdx >= 0:
if self.callback(heap, parentIdx, currentIdx):
swap(heap, parentIdx, currentIdx)
currentIdx = parentIdx
parentIdx = (currentIdx-1)//2
else:
return
def siftDown(self, heap, currentIdx, endIdx):
childOneIdx = 2*currentIdx + 1
while childOneIdx <= endIdx:
childTwoIdx = 2*currentIdx+2 if currentIdx*2+2 <= endIdx else -1
if childTwoIdx != -1 and self.callback(heap, childOneIdx, childTwoIdx):
idxSwapIdx = childTwoIdx
else:
idxSwapIdx = childOneIdx
if self.callback(heap, idxSwapIdx, currentIdx):
swap(heap, idxSwapIdx, currentIdx)
currentIdx = idxSwapIdx
childOneIdx = 2*currentIdx + 1
else:
return
def peek(self):
return self.heap[0]
def remove(self):
swap(self.heap, 0, len(self.heap)-1)
valueToRemove = self.heap.pop()
self.length -= 1
self.siftDown(self.heap, 0, len(self.heap)-1)
return valueToRemove
def insert(self, value):
self.heap.append(value)
self.length += 1
self.siftUp(self.heap, len(self.heap)-1)
def MAX_HEAP(array,idxOne,idxTwo):
return True if array[idxOne] > array[idxTwo] else False
def MIN_HEAP(array,idxOne,idxTwo):
return True if array[idxOne] < array[idxTwo] else False