15.04.2018 Views

programming-for-dummies

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

396<br />

Using Selection Sort<br />

32 9 9 32 With a short list, bubble sort can work quickly.<br />

Step #1<br />

Step #2<br />

74 32 21 9 With a long, unsorted list, bubble sort takes too much time.<br />

32 74 21 9<br />

Step #1<br />

21 9 32 74<br />

Step #5<br />

32 21 74 9<br />

Step #2<br />

21 9 32 74<br />

Step #6<br />

Figure 1-2:<br />

The bubble<br />

sort<br />

algorithm<br />

examines<br />

the entire<br />

list of data<br />

several<br />

times.<br />

32 21 9 74<br />

Step #3<br />

21 32 9 74<br />

Step #4<br />

9 21 32 74<br />

Final sorted list<br />

Using Selection Sort<br />

Another simple way to sort a list is to search the entire list until you find the<br />

smallest value. Then move that value to the front of the list. Now repeat the<br />

process all over again, skipping the first item. By repetitively searching <strong>for</strong><br />

the smallest item and moving it to the front of the list, the selection sort<br />

algorithm can eventually sort an entire list, as shown in Figure 1-3.<br />

The selection sort algorithm works like this:<br />

1. Find the smallest item in a list.<br />

2. Swap this value with the value currently at the front of the list.<br />

3. Repeat Steps 1 and 2 with the current size of the list minus one (list<br />

size = list size – 1).

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

Saved successfully!

Ooh no, something went wrong!