12.07.2015 Views

A Practical Introduction to Data Structures and Algorithm Analysis

A Practical Introduction to Data Structures and Algorithm Analysis

A Practical Introduction to Data Structures and Algorithm Analysis

SHOW MORE
SHOW LESS
  • No tags were found...

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

186 Chap. 5 Binary Trees172 34645 6 7123 5(a)1723564 5 6 74 2 1 3(b)Figure 5.20 Two series of exchanges <strong>to</strong> build a max-heap. (a) This heap is builtby a series of nine exchanges in the order (4-2), (4-1), (2-1), (5-2), (5-4), (6-3),(6-5), (7-5), (7-6). (b) This heap is built by a series of four exchanges in the order(5-2), (7-3), (7-1), (6-1).RH 1 H 2Figure 5.21 Final stage in the heap-building algorithm. Both subtrees of node Rare heaps. All that remains is <strong>to</strong> push R down <strong>to</strong> its proper level in the heap.array, with the first internal node. The exchanges shown in Figure 5.20(b) resultfrom this process. Method buildHeap implements the building algorithm.What is the cost of buildHeap? Clearly it is the sum of the costs for the calls<strong>to</strong> siftdown. Each siftdown operation can cost at most the number of levels ittakes for the node being sifted <strong>to</strong> reach the bot<strong>to</strong>m of the tree. In any complete tree,approximately half of the nodes are leaves <strong>and</strong> so cannot be moved downward atall. One quarter of the nodes are one level above the leaves, <strong>and</strong> so their elementscan move down at most one level. At each step up the tree we get half the number ofnodes as were at the previous level, <strong>and</strong> an additional height of one. The maximum

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!