Skip to content

Commit a84000e

Browse files
committed
Day40: add brainstorm thoughts about O(n) heapify
1 parent ef47d7d commit a84000e

File tree

2 files changed

+62
-0
lines changed

2 files changed

+62
-0
lines changed

day38/README.md

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -82,3 +82,60 @@ If some kind of ordering is required, i.e. max or min ordering, a heap is an
8282
efficient way to maintain that ordering even when elements are being deleted
8383
and added. The tree structure of the heap allows you to find elements in
8484
`O(logn)` time rather than `O(n)` time like in a normal array or linked list.
85+
86+
Some more thinking around heapify, aka just cram an unsorted array into
87+
a binary tree, and then compare and swap unordered parent-children pairs:
88+
89+
arr = [4, 5, 7, 3, 9, 6, 1]
90+
91+
4
92+
/ \
93+
5 7
94+
/ \ / \
95+
3 9 6 1
96+
97+
len = 7
98+
first parent = 7/2 = 3
99+
index = 3-1
100+
arr[index] == 7
101+
102+
7's children: arr[2*index + 1], arr[2*index + 2] aka 6, 1
103+
1 < 6
104+
105+
4
106+
/ \
107+
5 1
108+
/ \ / \
109+
3 9 6 7
110+
111+
next parent -> index -= 1
112+
arr[index] = 5
113+
114+
5's children: 3, 9
115+
3 < 9
116+
117+
4
118+
/ \
119+
3 1
120+
/ \ / \
121+
5 9 6 7
122+
123+
next parent -> index -= 1
124+
arr[index] = 4
125+
126+
4's children: 3, 1
127+
1 < 3
128+
129+
1
130+
/ \
131+
3 4
132+
/ \ / \
133+
5 9 6 7
134+
135+
done.
136+
137+
Need to do one comparison set for each parent node, and then done. So O(n) time!
138+
139+
140+
141+

day38/heap.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ def __init__(self, arr=[]):
77
if len(arr) > 0:
88
self.heapify(arr)
99

10+
# runtime: O(logn) aka the height of the heap
1011
def getMin(self):
1112
if self.size > 0:
1213
ret = self.heap.popleft()
@@ -16,19 +17,23 @@ def getMin(self):
1617
self.bubbleDown()
1718
return ret
1819

20+
# runtime: O(1)
1921
def peek(self):
2022
if self.size > 0:
2123
return self.heap[0]
2224

25+
# runtime: O(logn) aka the height of the tree
2326
def push(self, val):
2427
self.size += 1
2528
self.heap.append(val)
2629
self.bubbleUp()
2730

31+
# runtime: O(nlogn)
2832
def heapify(self, arr):
2933
for item in arr:
3034
self.push(item)
3135

36+
# runtime: O(1)
3237
def isEmpty(self):
3338
return self.size == 0
3439

0 commit comments

Comments
 (0)