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.

In-place quick-sort modifies the <strong>in</strong>put sequence us<strong>in</strong>g element swapp<strong>in</strong>g <strong>and</strong> does<br />

not explicitly create subsequences. Indeed, a subsequence of the <strong>in</strong>put sequence is<br />

implicitly represented by a range of positions specified by a left-most <strong>in</strong>dex l <strong>and</strong> a<br />

right-most <strong>in</strong>dex r. The divide step is performed by scann<strong>in</strong>g the array<br />

simultaneously from l forward <strong>and</strong> from r backward, swapp<strong>in</strong>g pairs of elements<br />

that are <strong>in</strong> reverse order, as shown <strong>in</strong> Figure 11.14. When these two <strong>in</strong>dices "meet,"<br />

subarrays L <strong>and</strong> G are on opposite sides of the meet<strong>in</strong>g po<strong>in</strong>t. The algorithm<br />

completes by recurr<strong>in</strong>g on these two subarrays.<br />

In-place quick-sort reduces the runn<strong>in</strong>g time caused by the creation of new<br />

sequences <strong>and</strong> the movement of elements between them by a constant factor. We<br />

show a <strong>Java</strong> version of <strong>in</strong>-place quick-sort <strong>in</strong> Code Fragment 11.7.<br />

Figure 11.14: Divide step of <strong>in</strong>-place quick-sort. Index<br />

l scans the sequence from left to right, <strong>and</strong> <strong>in</strong>dex r<br />

scans the sequence from right to left. A swap is<br />

performed when l is at an element larger than the pivot<br />

705

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

Saved successfully!

Ooh no, something went wrong!