Home » Bubble Sort

Bubble Sort

The Bubble sort uses an incremental approach. The following shows the sequence of steps in a Bubble Sort:


After the first pass we notice that the largest value (5) has “bubbled” its way to the end of the list; however, the array is still not in order. Continue to repeat this process until no swaps are made. Only then is the list in order. On each subsequent pass the next largest value will “bubble” its way to its correct position near the end of the list.

Making the swap:

Before presenting a method that will perform a Bubble sort we need to first understand how to swap the contents of two variables. This procedure is at the heart of several types of sorting. Suppose we wish to interchange the value of integers p and q and that their original values are:

p = 5 and q = 79

When finished with the swap, their values will be:

p = 79 and q = 5

This is accomplished with the following code where you will notice the presence of int temp which serves as a safe haven for the first variable while the swap is being made.

temp = p; p = q;

q = temp;