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.

Insertion-Sort<br />

If we implement the priority queue P us<strong>in</strong>g a sorted list, then we improve the<br />

runn<strong>in</strong>g time of Phase 2 to O(n), for each operation removeM<strong>in</strong> on P now takes<br />

O(1) time. Unfortunately, Phase 1 now becomes the bottleneck for the runn<strong>in</strong>g<br />

time, s<strong>in</strong>ce, <strong>in</strong> the worst case, each <strong>in</strong>sert operation takes time proportional to the<br />

size of P. This sort<strong>in</strong>g algorithm is therefore better known as <strong>in</strong>sertion-sort (see<br />

Figure 8.2), for the bottleneck <strong>in</strong> this sort<strong>in</strong>g algorithm <strong>in</strong>volves the repeated<br />

"<strong>in</strong>sertion" of a new element at the appropriate position <strong>in</strong> a sorted list.<br />

Figure 8.2: Execution of <strong>in</strong>sertion-sort on sequence<br />

S = (7,4,8,2,5,3,9). In Phase 1, we repeatedly remove<br />

the first element of S <strong>and</strong> <strong>in</strong>sert it <strong>in</strong>to P, by scann<strong>in</strong>g<br />

the list implement<strong>in</strong>g P, until we f<strong>in</strong>d the correct place<br />

for this element. In Phase 2, we repeatedly perform<br />

removeM<strong>in</strong> operations on P, each of which returns<br />

the first element of the list implement<strong>in</strong>g P, <strong>and</strong> we<br />

add the element at the end of S. Analyz<strong>in</strong>g the runn<strong>in</strong>g<br />

time of Phase 1 of <strong>in</strong>sertion-sort, we note that it is<br />

467

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

Saved successfully!

Ooh no, something went wrong!