19.12.2012 Views

Computer Programming Concepts and Visual Basic David I. Schneider

Computer Programming Concepts and Visual Basic David I. Schneider

Computer Programming Concepts and Visual Basic David I. Schneider

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

■ BUBBLE SORT<br />

The bubble sort is an algorithm that compares adjacent items <strong>and</strong> swaps those that are out of<br />

order. If this process is repeated enough times, the list will be ordered. Let’s carry out this<br />

process on the list Pebbles, Barney, Wilma, Fred, Dino. The steps for each pass through the list<br />

are as follows:<br />

1. Compare the first <strong>and</strong> second items. If they are out of order, swap them.<br />

2. Compare the second <strong>and</strong> third items. If they are out of order, swap them.<br />

3. Repeat this pattern for all remaining pairs. The final comparison <strong>and</strong> possible<br />

swap are between the second-to-last <strong>and</strong> last elements.<br />

The first time through the list, this process is repeated to the end of the list. This is called<br />

the first pass. After the first pass, the last item (Wilma) will be in its proper position. Therefore,<br />

the second pass does not have to consider it <strong>and</strong> so requires one less comparison. At the<br />

end of the second pass, the last two items will be in their proper position. (The items that<br />

must have reached their proper position have been underlined.) Each successive pass requires<br />

one less comparison. After four passes, the last four items will be in their proper positions,<br />

<strong>and</strong> hence, the first will be also.<br />

Sorting <strong>and</strong> Searching 185

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

Saved successfully!

Ooh no, something went wrong!