-
Notifications
You must be signed in to change notification settings - Fork 0
/
basic heaps
81 lines (68 loc) · 2.3 KB
/
basic heaps
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
class MinHeap:
def __init__(self):
self.heap_list = [None]
self.count = 0
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
def child_present(self, idx):
return self.left_child_idx(idx) <= self.count
def retrieve_min(self):
if self.count == 0:
print("No items in heap")
return None
min = self.heap_list[1]
self.heap_list[1] = self.heap_list[self.count]
self.count -= 1
self.heap_list.pop()
self.heapify_down()
return min
def add(self, element):
self.count += 1
self.heap_list.append(element)
self.heapify_up()
def get_smaller_child_idx(self, idx):
if self.right_child_idx(idx) > self.count:
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:
return self.left_child_idx(idx)
else:
return self.right_child_idx(idx)
def heapify_up(self):
idx = self.count
swap_count = 0
while self.parent_idx(idx) > 0:
if self.heap_list[self.parent_idx(idx)] > self.heap_list[idx]:
swap_count += 1
tmp = self.heap_list[self.parent_idx(idx)]
self.heap_list[self.parent_idx(idx)] = self.heap_list[idx]
self.heap_list[idx] = tmp
idx = self.parent_idx(idx)
element_count = len(self.heap_list)
if element_count > 10000:
print("Heap of {0} elements restored with {1} swaps"
.format(element_count, swap_count))
print("")
def heapify_down(self):
idx = 1
# starts at 1 because we swapped first and last elements
swap_count = 1
while self.child_present(idx):
smaller_child_idx = self.get_smaller_child_idx(idx)
if self.heap_list[idx] > self.heap_list[smaller_child_idx]:
swap_count += 1
tmp = self.heap_list[smaller_child_idx]
self.heap_list[smaller_child_idx] = self.heap_list[idx]
self.heap_list[idx] = tmp
idx = smaller_child_idx
element_count = len(self.heap_list)
if element_count >= 10000:
print("Heap of {0} elements restored with {1} swaps"
.format(element_count, swap_count))
print("")