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.

The quick-sort algorithm sorts a sequence S us<strong>in</strong>g a simple recursive approach. The<br />

ma<strong>in</strong> idea is to apply the divide-<strong>and</strong>-conquer technique, whereby we divide S <strong>in</strong>to<br />

subsequences, recur to sort each subsequence, <strong>and</strong> then comb<strong>in</strong>e the sorted<br />

subsequences by a simple concatenation. In particular, the quick-sort algorithm<br />

consists of the follow<strong>in</strong>g three steps (see Figure 11.8):<br />

1. Divide: If S has at least two elements (noth<strong>in</strong>g needs to be done if S has<br />

zero or one element), select a specific element x from S, which is called the pivot.<br />

As is common practice, choose the pivot x to be the last element <strong>in</strong> S. Remove all<br />

the elements from S <strong>and</strong> put them <strong>in</strong>to three sequences:<br />

• L, stor<strong>in</strong>g the elements <strong>in</strong> S less than x<br />

• E, stor<strong>in</strong>g the elements <strong>in</strong> S equal to x<br />

• G, stor<strong>in</strong>g the elements <strong>in</strong> S greater than x.<br />

Of course, if the elements of S are all dist<strong>in</strong>ct, then E holds just one element—the<br />

pivot itself.<br />

2. Recur: Recursively sort sequences L <strong>and</strong> G.<br />

3. Conquer: Put back the elements <strong>in</strong>to S <strong>in</strong> order by first <strong>in</strong>sert<strong>in</strong>g the<br />

elements of L, then those of E, <strong>and</strong> f<strong>in</strong>ally those of G.<br />

Figure 11.8:<br />

algorithm.<br />

A visual schematic of the quick-sort<br />

Like merge-sort, the execution of quick-sort can be visualized by means of a b<strong>in</strong>ary<br />

recursion tree, called the quick-sort tree. Figure 11.9 summarizes an execution of<br />

the quick-sort algorithm by show<strong>in</strong>g the <strong>in</strong>put <strong>and</strong> output sequences processed at<br />

694

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

Saved successfully!

Ooh no, something went wrong!