-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHeap.py
More file actions
92 lines (77 loc) · 2.95 KB
/
Heap.py
File metadata and controls
92 lines (77 loc) · 2.95 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
84
85
86
87
88
89
90
91
92
class MinHeap:
def __init__(self):
self.heap_list = [None]
self.count = 0
# HEAP HELPER METHODS
# DO NOT CHANGE!
def parent_idx(self, idx):
return idx // 2
def left_child_idx(self, idx):
return idx * 2
def right_child_idx(self, idx):
return idx * 2 + 1
# NEW HELPER!
def child_present(self, idx):
return self.left_child_idx(idx) <= self.count
# END OF HEAP HELPER METHODS
def retrieve_min(self):
if self.count == 0:
print("No items in heap")
return None
min = self.heap_list[1]
print("Removing: {0} from {1}".format(min, self.heap_list))
self.heap_list[1] = self.heap_list[self.count]
self.count -= 1
self.heap_list.pop()
print("Last element moved to first: {0}".format(self.heap_list))
self.heapify_down()
return min
def add(self, element):
self.count += 1
print("Adding: {0} to {1}".format(element, self.heap_list))
self.heap_list.append(element)
self.heapify_up()
def heapify_down(self):
idx = 1
while self.child_present(idx):
print("Heapifying down!")
smaller_child_idx = self.get_smaller_child_idx(idx)
child = self.heap_list[smaller_child_idx]
parent = self.heap_list[idx]
if parent > child:
self.heap_list[idx] = child
self.heap_list[smaller_child_idx] = parent
idx = smaller_child_idx
print("HEAP RESTORED! {0}".format(self.heap_list))
def get_smaller_child_idx(self, idx):
if self.right_child_idx(idx) > self.count:
print("There is only a left child")
return self.left_child_idx(idx)
else:
left_child = self.heap_list[self.left_child_idx(idx)]
right_child = self.heap_list[self.right_child_idx(idx)]
if left_child < right_child:
print("Left child is smaller")
return self.left_child_idx(idx)
else:
print("Right child is smaller")
return self.right_child_idx(idx)
def heapify_up(self):
idx = self.count
while self.parent_idx(idx) > 0:
if self.heap_list[self.parent_idx(idx)] > self.heap_list[idx]:
tmp = self.heap_list[self.parent_idx(idx)]
print("swapping {0} with {1}".format(tmp, self.heap_list[idx]))
self.heap_list[self.parent_idx(idx)] = self.heap_list[idx]
self.heap_list[idx] = tmp
idx = self.parent_idx(idx)
print("HEAP RESTORED! {0}".format(self.heap_list))
print("")
# make an instance of MinHeap
min_heap = MinHeap()
# set internal list for testing purposes...
min_heap.heap_list = [None, 10, 13, 21, 61, 22, 23, 99]
min_heap.count = 7
while len(min_heap.heap_list) != 1:
print(min_heap.heap_list)
min_heap.retrieve_min()