11.07.2015 Views

Data Structures and Algorithm Analysis - Computer Science at ...

Data Structures and Algorithm Analysis - Computer Science at ...

Data Structures and Algorithm Analysis - Computer Science at ...

SHOW MORE
SHOW LESS

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

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

Sec. 5.5 Heaps <strong>and</strong> Priority Queues 175172 34645 6 7123 5(a)1723564 5 6 74 2 1 3(b)Figure 5.20 Two series of exchanges to 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).Each call to insert takes Θ(log n) time in the worst case, because the valuebeing inserted can move <strong>at</strong> most the distance from the bottom of the tree to the topof the tree. Thus, to insert n values into the heap, if we insert them one <strong>at</strong> a time,will take Θ(n log n) time in the worst case.If all n values are available <strong>at</strong> the beginning of the building process, we canbuild the heap faster than just inserting the values into the heap one by one. ConsiderFigure 5.20(a), which shows one series of exchanges th<strong>at</strong> could be used tobuild the heap. All exchanges are between a node <strong>and</strong> one of its children. The heapis formed as a result of this exchange process. The array for the right-h<strong>and</strong> tree ofFigure 5.20(a) would appear as follows:7 4 6 1 2 3 5Figure 5.20(b) shows an altern<strong>at</strong>e series of exchanges th<strong>at</strong> also forms a heap,but much more efficiently. The equivalent array represent<strong>at</strong>ion would be7 5 6 4 2 1 3From this example, it is clear th<strong>at</strong> the heap for any given set of numbers is notunique, <strong>and</strong> we see th<strong>at</strong> some rearrangements of the input values require fewer exchangesthan others to build the heap. So, how do we pick the best rearrangement?

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

Saved successfully!

Ooh no, something went wrong!