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.

Actually, we can show that the runn<strong>in</strong>g time of r<strong>and</strong>omized quick-sort is O(nlogn)<br />

with high probability. (See Exercise C-11.10.)<br />

11.2.2 In-Place Quick-Sort<br />

Recall from Section 8.3.5 that a sort<strong>in</strong>g algorithm is <strong>in</strong>-place if it uses only a small<br />

amount of memory <strong>in</strong> addition to that needed for the objects be<strong>in</strong>g sorted<br />

themselves. The merge-sort algorithm, as we have described it above, is not <strong>in</strong>place,<br />

<strong>and</strong> mak<strong>in</strong>g it be <strong>in</strong>-place requires a more complicated merg<strong>in</strong>g method than<br />

the one we discuss <strong>in</strong> Section 11.1.2. In-place sort<strong>in</strong>g is not <strong>in</strong>herently difficult,<br />

however. For, as with heap-sort, quick-sort can be adapted to be <strong>in</strong>-place.<br />

Perform<strong>in</strong>g the quick-sort algorithm <strong>in</strong>-place requires a bit of <strong>in</strong>genuity, however,<br />

for we must use the <strong>in</strong>put sequence itself to store the subsequences for all the<br />

recursive calls. We show algorithm <strong>in</strong>PlaceQuickSort, which performs <strong>in</strong>place<br />

quick-sort, <strong>in</strong> Code Fragment 11.6. Algorithm <strong>in</strong>PlaceQuickSort<br />

assumes that the <strong>in</strong>put sequence, S, is given as an array of dist<strong>in</strong>ct elements. The<br />

reason for this restriction is explored <strong>in</strong> Exercise R-11.14. The extension to the<br />

general case is discussed <strong>in</strong> Exercise C-11.8.<br />

Code Fragment 11.6:<br />

<strong>in</strong>put array S.<br />

In-place quick-sort for an<br />

704

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

Saved successfully!

Ooh no, something went wrong!