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

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

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

E has at least one element (the pivot), the sum of the <strong>in</strong>put sizes of the children of v<br />

is atmosts(v) − 1.<br />

Given a quick-sort tree T, let s i denote the sum of the <strong>in</strong>put sizes of the nodes at<br />

depth i <strong>in</strong> T. Clearly, s 0 = n, s<strong>in</strong>ce the root r of T is associated with the entire<br />

sequence. Also, s 1 ≤ n − 1, s<strong>in</strong>ce the pivot is not propagated to the children of r.<br />

Consider next s 2 . If both children of r have nonzero <strong>in</strong>put size, then s 2 = n − 3.<br />

Otherwise (one child of the root has zero size, the other has size n − 1), s 2 = n − 2.<br />

Thus, s 2 ≤ n − 2. Cont<strong>in</strong>u<strong>in</strong>g this l<strong>in</strong>e of reason<strong>in</strong>g, we obta<strong>in</strong> that s i ≤ n − i. As<br />

observed <strong>in</strong> Section 11.2, the height of T is n − 1 <strong>in</strong> the worst case. Thus, the worstcase<br />

runn<strong>in</strong>g time of quick-sort is , which is , that is,<br />

time.<br />

. By Proposition 4.3, . Thus, quick-sort runs <strong>in</strong> O(n 2 ) worst-case<br />

Given its name, we would expect quick-sort to run quickly. However, the quadratic<br />

bound above <strong>in</strong>dicates that quick-sort is slow <strong>in</strong> the worst case. Paradoxically, this<br />

worst-case behavior occurs for problem <strong>in</strong>stances when sort<strong>in</strong>g should be easy—if<br />

the sequence is already sorted.<br />

Go<strong>in</strong>g back to our analysis, note that the best case for quick-sort on a sequence of<br />

dist<strong>in</strong>ct elements occurs when subsequences L <strong>and</strong> G happen to have roughly the<br />

same size. That is, <strong>in</strong> the best case, we have<br />

s 0<br />

=<br />

n<br />

s 1<br />

=<br />

n − 1<br />

s 2<br />

=<br />

n − (1 + 2) = n − 3<br />

<br />

s i<br />

=<br />

701

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

Saved successfully!

Ooh no, something went wrong!