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.

176 Chap. 5 Binary TreesRH1H2Figure 5.21 Final stage in the heap-building algorithm. Both subtrees of node Rare heaps. All th<strong>at</strong> remains is to push R down to its proper level in the heap.177575 15 64 2 6 3 4 2 6 3 4 2 1 3(a) (b) (c)Figure 5.22 The siftdown oper<strong>at</strong>ion. The subtrees of the root are assumed tobe heaps. (a) The partially completed heap. (b) Values 1 <strong>and</strong> 7 are swapped.(c) Values 1 <strong>and</strong> 6 are swapped to form the final heap.One good algorithm stems from induction. Suppose th<strong>at</strong> the left <strong>and</strong> right subtreesof the root are already heaps, <strong>and</strong> R is the name of the element <strong>at</strong> the root.This situ<strong>at</strong>ion is illustr<strong>at</strong>ed by Figure 5.21. In this case there are two possibilities.(1) R has a value gre<strong>at</strong>er than or equal to its two children. In this case, constructionis complete. (2) R has a value less than one or both of its children. In this case,R should be exchanged with the child th<strong>at</strong> has gre<strong>at</strong>er value. The result will be aheap, except th<strong>at</strong> R might still be less than one or both of its (new) children. Inthis case, we simply continue the process of “pushing down” R until it reaches alevel where it is gre<strong>at</strong>er than its children, or is a leaf node. This process is implementedby the priv<strong>at</strong>e method siftdown. The siftdown oper<strong>at</strong>ion is illustr<strong>at</strong>ed byFigure 5.22.This approach assumes th<strong>at</strong> the subtrees are already heaps, suggesting th<strong>at</strong> acomplete algorithm can be obtained by visiting the nodes in some order such th<strong>at</strong>the children of a node are visited before the node itself. One simple way to do thisis simply to work from the high index of the array to the low index. Actually, thebuild process need not visit the leaf nodes (they can never move down because theyare already <strong>at</strong> the bottom), so the building algorithm can start in the middle of thearray, with the first internal node. The exchanges shown in Figure 5.20(b) resultfrom this process. Method buildHeap implements the building algorithm.Wh<strong>at</strong> is the cost of buildHeap? Clearly it is the sum of the costs for the callsto siftdown. Each siftdown oper<strong>at</strong>ion can cost <strong>at</strong> most the number of levels it

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

Saved successfully!

Ooh no, something went wrong!