Visual Basic 2008 Programming: Business Applications with a Design Perspective
Chapter 1 Chapter 2 Chapter 3 Chapter 4 Chapter 5 Chapter 6 Chapter 7 Chapter 8 Chapter 9
Chapter 10 Chapter 11 Chapter 12 Chapter 13 Chapter 14 Appendix A Appendix B Appendix C Home
Loading
Last change: February 13 2016 18:48:19.

 Chapter in PDF

Table of Contents

Appendix C: Sorting and Searching
Last change: February 13 2016 18:48:22.
<<PreviousNext>>

C.1 Bubble Sort

In the bubble sort, each element in the array is compared with the next element. If these elements are out of order, they are swapped. When one round of comparisons (and the resulting swaps) is done, the largest value in the array will be placed at the right-most position as a result. As a result, one fewer element need be compared in the next round. This process continues until the final round in which only two elements need to be compared.

The process is illustrated in the following example.
Position           1          2          3          4          5
Value              38        51        23        56        34

The comparisons start from left to right, element by element. The first element, 38, is compared with the second element, 51. Because they are in order, nothing is moved. The second element, 51, is then compared with the third element, 23. Because they are out of order, the two elements are swapped. The result appears as follows:
Position           1          2          3          4          5
Value               38        23        51        56        34
The third element, now 51, is compared with the fourth element, 56; then 56 is compared with 34, resulting in another swap. After the first round of comparison, the array will appear as follows:
Position           1          2          3          4          5
Value               38        23        51        34        56
Notice that the largest element in the array is now at the right-most position.

The same process of comparisons for the second round will start from position 1 again, but will stop at position 4, resulting in the second largest element being moved into this position. This process is repeated until all elements are placed in their proper position.
Last change: February 13 2016 18:48:23.
  1. C.1 Bubble Sort
    1. Comparing and Swapping
    2. The Number of Elements to Compare
    3. The Number of Rounds of Comparisons
    4. Computing the Number of Comparisons for Each Round
    5. The Bubble Sort Sub Procedure
    6. Testing the Procedure
    7. Expected Behavior of the Testing Project
    8. Declaring the Array
    9. Generating the Random Numbers
    10. Calling the Sorting Sub and Displaying the Results
    11. Computing Time Used
    12. A Remark on Sorting Efficiency
    13. Simple Selection Sort
    14. <<PreviousNext>>