23.11.2014 Views

Data Structures and Algorithms in Java[1].pdf - Fulvio Frisone

Data Structures and Algorithms in Java[1].pdf - Fulvio Frisone

Data Structures and Algorithms in Java[1].pdf - Fulvio Frisone

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Bottom-up heap construction is asymptotically faster than <strong>in</strong>crementally <strong>in</strong>sert <strong>in</strong>g<br />

n keys <strong>in</strong>to an <strong>in</strong>itially empty heap, as the follow<strong>in</strong>g proposition shows.<br />

Proposition 8.7: Bottom-up construction of a heap with n entries takes<br />

O(n) time, assum<strong>in</strong>g two keys can be compared <strong>in</strong> O(1) time.<br />

Justification: We analyze bottom-up heap construction us<strong>in</strong>g a "visual" ap<br />

proach, which is illustrated <strong>in</strong> Figure 8.11.<br />

Let T be the f<strong>in</strong>al heap, let v be a node of T, <strong>and</strong> let T(v) denote the subtree of T<br />

rooted at v. In the worst case, the time for form<strong>in</strong>g T(v) from the two recursively<br />

formed subtrees rooted at v's children is proportional to the height of T(v). The<br />

worst case occurs when down-heap bubbl<strong>in</strong>g from v traverses a path from v all the<br />

way to a bottom-most node of T(v).<br />

Now consider the path p(v) of T from node v to its <strong>in</strong>order successor external<br />

node, that is, the path that starts at v, goes to the right child of v, <strong>and</strong> then goes<br />

down leftward until it reaches an external node. We say that path p(v) is<br />

associated with node v. Note that p(v) is not necessarily the path followed by<br />

down-heap bubbl<strong>in</strong>g when form<strong>in</strong>g T(v). Clearly, the size (number of nodes) of<br />

p(v) is equal to the height of T(v) plus one. Hence, form<strong>in</strong>g T(v) takes time<br />

proportional to the size of ofp(v), <strong>in</strong> the worst case. Thus, the total runn<strong>in</strong>g time of<br />

bottom-up heap construction is proportional to the sum of the sizes of the paths<br />

associated with the nodes of T.<br />

Observe that each node v of T dist<strong>in</strong>ct from the root belongs to exactly two such<br />

paths: the path p(v) associated with v itself <strong>and</strong> the path p(u) associated with the<br />

parent u of v. (See Figure 8.11.) Also, the root r of T belongs only to path p(r)<br />

associated with r itself. Therefore, the sum of the sizes of the paths associated<br />

with the <strong>in</strong>ternal nodes of T is 2n − 1. We conclude that the bottom-up<br />

construction of heap T takes O(n) time.<br />

494

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

Saved successfully!

Ooh no, something went wrong!