-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmax_heap.py
More file actions
66 lines (51 loc) · 1.82 KB
/
Copy pathmax_heap.py
File metadata and controls
66 lines (51 loc) · 1.82 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
class MaxHeap:
def __init__(self):
self.elements = []
def pop(self):
if len(self.elements) == 0:
return None
if len(self.elements) == 1:
return self.elements.pop()
root_value = self.elements[0]
self.elements[0] = self.elements.pop()
self.bubble_down(0)
return root_value
def bubble_down(self, index):
left_child_index = 2 * index + 1
right_child_index = 2 * index + 2
max_index = index
if (
left_child_index < len(self.elements)
and self.elements[left_child_index][0] > self.elements[max_index][0]
):
max_index = left_child_index
if (
right_child_index < len(self.elements)
and self.elements[right_child_index][0] > self.elements[max_index][0]
):
max_index = right_child_index
if max_index != index:
self.elements[index], self.elements[max_index] = (
self.elements[max_index],
self.elements[index],
)
self.bubble_down(max_index)
def push(self, priority, value):
self.elements.append((priority, value))
self.bubble_up(len(self.elements) - 1)
def bubble_up(self, index):
if index == 0:
return
parent_index = (index - 1) // 2
parent_priority = self.elements[parent_index][0]
current_priority = self.elements[index][0]
if parent_priority < current_priority:
self.elements[parent_index], self.elements[index] = (
self.elements[index],
self.elements[parent_index],
)
self.bubble_up(parent_index)
def peek(self):
if len(self.elements) == 0:
return None
return self.elements[0][1]