@@ -62,7 +62,7 @@ push - takes an integer as an argument and adds it into the heap, returning
6262 nothing. Should complete in ` O(logn) ` time.
6363
6464heapify - takes an array of integers and forms a heap out of them. Should run in
65- ` O(nlogn) ` (?) time.
65+ ` O(n) ` time.
6666
6767size - takes no arguments and returns the number of integers in the heap ` n `
6868 in ` O(1) ` time.
@@ -83,8 +83,20 @@ efficient way to maintain that ordering even when elements are being deleted
8383and 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.
8585
86+ ---
87+
8688Some more thinking around heapify, aka just cram an unsorted array into
87- a binary tree, and then compare and swap unordered parent-children pairs:
89+ a binary tree, and then compare and swap unordered parent-children pairs,
90+ from the bottom up:
91+
92+ arr = [ 7, 6, 5, 4, 3, 2, 1]
93+
94+ 1
95+ / \
96+ 3 2
97+ / \ / \
98+ 4 6 7 5
99+
88100
89101arr = [ 4, 5, 7, 3, 9, 6, 1]
90102
@@ -134,8 +146,19 @@ arr[index] = 4
134146
135147done.
136148
137- Need to do one comparison set for each parent node, and then done. So O(n) time!
149+ Need to do one bubbleDown each parent node from the bottom up, and then done.
150+ On the bottom-most level, ` n/2 ` nodes can move at most 0 levels down.
151+ Next level, ` n/4 ` nodes can move at most 1 level down.
152+ etc.
153+
154+ So it's a summation on i from 0 to logn:
138155
156+ ` n/(2**i) * i `
139157
158+ which turns out to be ` O(n) ` work!
140159
160+ Edit: fix ` heapify ` code.
141161
162+ For more information:
163+ - https://www.cs.umd.edu/~meesh/351/mount/lectures/lect14-heapsort-analysis-part.pdf
164+ - https://www.youtube.com/watch?v=MiyLo8adrWw
0 commit comments