Bubble Sort Algorithm with an Example

This post was created and published to describe a mechanism used to sort numbers or elements of an array, which is "bubble sort." I included the algorithm along with an example regarding the "bubble sort."

Bubble Sort Algorithm

The following is the algorithm that is utilized when using bubble sort to sort a list of elements:

Note: Number of pass = total number of element in the array.

As a result, we must run the total number or amount of swapping methods as described above.

Bubble Sort Example

For example, if we have a total of 10 elements in an array, then we have to perform swapping 10 times, as shown in the example given below.

And as we all know, indexing in an array starts at 0, so we have to start from 0 to 9 if the total number of elements is 10.

Let's suppose the size of array is 10 and its elements are 10 1 9 2 8 3 7 4 6 5. Then follow these swapping instructions for the first pass:

1 9 2 8 3 7 4 6 5 10

starts with the very first two elements. Compare 1 and 9. It is already in sorted form. As a result, no swapping occurs.

1 9 2 8 3 7 4 6 5 10

Now compare 9 and 2. Because 2 is less than 9, swapping is carried out.

1 2 9 8 3 7 4 6 5 10

Compare 9 and 8. Because 8 is less than 9, swapping is performed once more.

1 2 8 9 3 7 4 6 5 10

Compare 9 and 3. 3 is less than 9. Swapping is carried out.

1 2 8 3 9 7 4 6 5 10

Compare 9 and 7. 7 is less than 9. Swapping is carried out.

1 2 8 3 7 9 4 6 5 10

Compare 9 and 4. 4 is less than 9. Swapping is carried out.

1 2 8 3 7 4 9 6 5 10

Compare 9 and 6. 6 is less than 9. Swapping is carried out.

1 2 8 3 7 4 6 9 5 10

Compare 9 and 5. 5 is less than 9. Swapping is carried out.

1 2 8 3 7 4 6 5 9 10

Compare 9 and 10. It is already in sorted form. As a result, no swapping occurs. And after 1st. The array looks like this:

1 2 8 3 7 4 6 5 9 10

In this way, all the passes get executed. Here is the step-by-step sorting of the array after each complete pass:

1 9 2 8 3 7 4 6 5 10
1 2 8 3 7 4 6 5 9 10
1 2 3 7 4 6 5 8 9 10
1 2 3 4 6 5 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10

So the final array will be 1 2 3 4 5 6 7 8 9 10.

Programs Created on Bubble Sort

Computer Fundamentals Quiz


« Previous Tutorial Next Tutorial »


Liked this post? Share it!