Introduction

The bubble sort algorithm is a simple sorting algorithm that can be implemented on any data which can be directly compared.

Steps of the algorithm

  1. Organize your data in a row such as an array
  2. Start with the first item. Compare it to the one after and swap the two items if the first item is larger than the second one.
  3. Move over one place and repeat step 2.
  4. Repeat step 3 until you reach the end of the row.
  5. Repeat steps 2 - 4 until you do a complete pass with no swaps. Your data is now sorted!

Example

Consider you have the numbers 3 8 5 2 in that order as shown below

We first look at 3 and 8. 3 is smaller than 8 so we do not swap them. We then move to 8 and 5. 8 is larger than 5 so we swap them. Our numbers are now in this order

Then we look at 8 and 2. 8 is larger than 2 so we swap them. We have now hit the end of the list and after our first complete pass our list is now

Now in the second pass, 3 and 5 are not swapped, 5 and 2 are swapped, and then 5 and 8 are not swapped so we have

In the next pass, only 3 and 2 are swapped

Now when we do a pass, no swaps are made. The list is now sorted and our final list is


For more information about this algorithm, check out this website