Bubble sort

An example of a computer algorithm is bubble sort. This is a simple algorithm used for taking a list of jumbled up numbers and putting them into the correct order. The algorithm runs as follows:

  1. Look at the first number in the list.
  2. Compare the current number with the next number.
  3. Is the next number smaller than the current number? If so, swap the two numbers around. If not, do not swap.
  4. Move to the next number along in the list and make this the current number.
  5. Repeat from step 2 until the last number in the list has been reached.
  6. If any numbers were swapped, repeat again from step 1.
  7. If the end of the list is reached without any swaps being made, then the list is ordered and the algorithm can stop.

Bubble sort example

This algorithm could be used to sort the following list:

3, 2, 4, 1, 5

The first loop of the algorithm would produce:

  • 3, 2, 4, 1, 5 (2<3 so the two values are swapped)
  • 2, 3, 4, 1, 5 (3<4 so the two values are not swapped)
  • 2, 3, 4, 1, 5 (1<4 so the two values are swapped)
  • 2, 3, 1, 4, 5 (4<5 so the two values are not swapped)
  • 2, 3, 1, 4, 5 (First pass completed)

Values were swapped so the algorithm needs to run again. The second loop of the algorithm would start with the final list and run again as follows:

  • 2, 3, 1, 4, 5 (2<3 so the values are not swapped)
  • 2, 3, 1, 4, 5 (1<3 so the values are swapped)
  • 2, 1, 3, 4, 5 (3<4 so the values are not swapped)
  • 2, 1, 3, 4, 5 (4<5 so the values are not swapped)
  • 2, 1, 3, 4, 5 (Second pass completed)
  • 2, 1, 3, 4, 5 (1<2 so the values are swapped)
  • 1, 2, 3, 4, 5 (2<3 so the values are not swapped)
  • 1, 2, 3, 4, 5 (3<4 so the values are not swapped)
  • 1, 2, 3, 4, 5 (4<5 so the values are not swapped)
  • 1, 2, 3, 4, 5 (Third pass completed)

Values were swapped so the algorithm needs to run again. This time there will be no swaps as the values are in order:

1, 2, 3, 4, 5

The algorithm has completed a loop without swapping anything and so it knows that the list is now ordered and can stop.