Visual Basic 2010 (Console) Guide
Bubble Sort

The bubble sort is a slow but simple method of sorting elements in a one-dimensional array.

It works as follows,

  1. Compare the first item in the list with the second.
  2. If they are in the wrong order, swap them around.
  3. Compare the second item to the third item.
  4. If they are in the wrong order, swap them around.
  5. Continue doing this until the end of the array.
  6. If you have had to swap any items, repeat the process until no swaps are made.

Take the following array of numbers,

2, 23, 9, 79, 31, 81, 53, 13, 33, 43

On the first pass, some items are swapped, leaving the list as follows,

2, 9, 23, 31, 79, 53, 13, 33, 43, 81

The process is repeated and further swaps are made,

2, 9, 23, 31, 53, 13, 33, 43, 79, 81

Third pass,

2, 9, 23, 31, 13, 33, 43, 53, 79, 81

Fourth pass,

2, 9, 23, 13, 31, 33, 43, 53, 79, 81

Fifth pass,

2, 9, 13, 23, 31, 33, 43, 53, 79, 81

We made some swaps on the last pass, so we still repeat the process. No swaps are made on the sixth pass, so the list is in order,

2, 9, 13, 23, 31, 33, 43, 53, 79, 81

Bubble Sort Algorithm

Repeat
   swapflag = false
   For count = 1 To N - 1
      If bubbleItem[count]>bubbleItem[count + 1] Then
         temp = bubbleItem[count]
         bubbleItem[count] = bubbleItem[count + 1]
         bubbleItem[count + 1] = temp
         swapflag = true
      End If
   Next
   N = N - 1
Until swapflag = false Or N = 1

Having A Go

  1. Write a Visual Basic program that implements the bubble sort on an array of random numbers. The easiest way to do this is to use numbers between 0 and 1. The double data type is best for this.