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.

8.2.3 Selection-Sort <strong>and</strong> Insertion-Sort<br />

Recall the PriorityQueueSort scheme <strong>in</strong>troduced <strong>in</strong> Section 8.1.4. We are<br />

given an unsorted sequence S conta<strong>in</strong><strong>in</strong>g n elements, which we sort us<strong>in</strong>g a priority<br />

queue P <strong>in</strong> two phases. In Phase 1 we <strong>in</strong>sert all the elements <strong>in</strong>to P <strong>and</strong> <strong>in</strong> Phase 2<br />

we repeatedly remove the elements from P us<strong>in</strong>g the removeM<strong>in</strong>() method.<br />

Selection-Sort<br />

If we implement P with an unsorted list, then Phase 1 of PriorityQueueSort<br />

takes O(n) time, for we can <strong>in</strong>sert each element <strong>in</strong> O(1) time. In Phase 2, the<br />

runn<strong>in</strong>g time of each removeM<strong>in</strong> operation is proportional to the size of P.<br />

Thus, the bottleneck computation is the repeated "selection" of the m<strong>in</strong>imum<br />

element <strong>in</strong> Phase 2. For this reason, this algorithm is better known as selectionsort.<br />

(See Figure 8.1.)<br />

As noted above, the bottleneck is <strong>in</strong> Phase 2 where we repeatedly remove an entry<br />

with smallest key from the priority queue P. The size of P starts at n <strong>and</strong><br />

<strong>in</strong>crementally decreases with each removeM<strong>in</strong> until it becomes 0. Thus, the first<br />

removeM<strong>in</strong> operation takes time O(n), the second one takes time O(n − 1), <strong>and</strong><br />

so on, until the last (nth) operation takes time O(1). Therefore, the total time<br />

needed for the second phase is<br />

.<br />

By Proposition 4.3, we have<br />

O(n 2 ), as does the entire selection-sort algorithm.<br />

. Thus, Phase 2 takes time<br />

Figure 8.1: Execution of selection-sort on sequence<br />

S = (7,4,8,2,5,3,9).<br />

466

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

Saved successfully!

Ooh no, something went wrong!