EECS 311: Chapter 6 Notes Chris Riesbeck EECS Northwestern
Unless otherwise noted, all tables, graphs and code from Mark Allen Weiss' Data Structures and Algorithm Analysis in C++, 3 rd ed, copyright © 2006 by Pearson Education, Inc.
Building the Initial Heap Given a set of numbers You could insert one by one Complexity: O(n log n) There's a better way… Throw all numbers into the array Fix from the bottom up (2 nd to last row)
Building a Heap Initial setProcess node 7
Building a Heap 2 Process node 5Process node 6
Building a Heap 3 Process node 3Process node 4
Building a Heap 4 Process node 1Process node 2
Building a Heap Complexity The worst case this way is the sum of the heights of the nodes. That sum = 2 h+1 – h 2 h+1 is the number of nodes N Ergo, this algorithm is O(N) to build a heap