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.

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

Aga<strong>in</strong>, by recall<strong>in</strong>g Proposition 4.3, Phase 1 runs <strong>in</strong> O(n 2 ) time, <strong>and</strong> hence, so<br />

does the entire <strong>in</strong>sertion-sort algorithm.<br />

Alternatively, we could change our def<strong>in</strong>ition of <strong>in</strong>sertion-sort so that we <strong>in</strong>sert<br />

elements start<strong>in</strong>g from the end of the priority-queue list <strong>in</strong> Phase 1, <strong>in</strong> which case<br />

perform<strong>in</strong>g <strong>in</strong>sertion-sort on a sequence that is already sorted would run <strong>in</strong> O(n)<br />

time. Indeed, the runn<strong>in</strong>g time of <strong>in</strong>sertion-sort <strong>in</strong> this case is O(n + I), where I is<br />

the number of <strong>in</strong>versions <strong>in</strong> the sequence, that is, the number of pairs of elements<br />

that start out <strong>in</strong> the <strong>in</strong>put sequence <strong>in</strong> the wrong relative order.<br />

8.3 Heaps<br />

The two implementations of the PriorityQueueSort scheme presented <strong>in</strong> the<br />

previous section suggest a possible way of improv<strong>in</strong>g the runn<strong>in</strong>g time for priorityqueue<br />

sort<strong>in</strong>g. For one algorithm (selection-sort) achieves a fast runn<strong>in</strong>g time for<br />

Phase 1, but has a slow Phase 2, whereas the other algorithm (<strong>in</strong>sertion-sort) has a<br />

slow Phase 1, but achieves a fast runn<strong>in</strong>g time for Phase 2. If we can somehow<br />

balance the runn<strong>in</strong>g times of the two phases, we might be able to significantly speed<br />

up the overall runn<strong>in</strong>g time for sort<strong>in</strong>g. This is, <strong>in</strong> fact, exactly what we can achieve<br />

us<strong>in</strong>g the priority-queue implementation discussed <strong>in</strong> this section.<br />

468

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

Saved successfully!

Ooh no, something went wrong!