-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathheap.py
More file actions
83 lines (66 loc) · 2.25 KB
/
heap.py
File metadata and controls
83 lines (66 loc) · 2.25 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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
class Heap:
def __init__(self, t, size):
self.heap = t
self.size = size
self.buildHeap()
def leftChild(self, index):
return 2 * index + 1
def rightChild(self, index):
return 2 * index + 2
def parentIndex(self, index):
return (index - 1) // 2
def heapify(self, index):
left = self.leftChild(index)
right = self.rightChild(index)
largest = index
if (left < self.size) and (self.heap[left] > self.heap[largest]):
largest = left
if (right < self.size) and (self.heap[right] > self.heap[largest]):
largest = right
if largest != index:
self.heap[index], self.heap[largest] = self.heap[largest], self.heap[index]
self.heapify(largest)
def buildHeap(self):
for index in range((len(self.heap) // 2)-1, -1, -1): # idziemy od tylu
self.heapify(index)
def display(self):
for value in self.heap[:self.size]:
print(f"{value} ", end="")
print("")
def getMax(self):
if self.size == 0:
return None
return self.heap[0]
def extractMax(self):
if self.size < 1:
return None
max = self.heap[0]
self.heap[0] = self.heap[self.size - 1]
self.size -= 1
self.heapify(0)
return max
def increaseKey(self, index, newValue):
self.heap[index] = newValue
while index > 0 and (self.heap[self.parentIndex(index)] < newValue):
parent = self.parentIndex(index)
temp = self.heap[index]
self.heap[index] = self.heap[parent]
self.heap[parent] = temp
index = parent
def insert(self, value):
self.size += 1
if self.size > len(self.heap):
self.heap.append(float('-inf')) # bardzo mala wartosc, zeby kolejnosc sie nie popsula
else:
self.heap[self.size - 1] = float('-inf')
self.increaseKey(self.size - 1, value)
heap = Heap([4, 1, 3, 2, 16, 9, 10, 14, 8, 7], 10)
heap.display()
heap.insert(15)
heap.display()
print(heap.getMax())
heap.display()
print(heap.extractMax())
heap.display()
heap.increaseKey(4, 19)
heap.display()