×
☰ Menu

Bubble Sort

Bubble sort is a simple sorting method. This sorting method is a comparison-based algorithm in which each pair of adjacent elements is compared, and if they are not in order, the elements are swapped.

As items are sorted in the bubble sort, they "bubble" (or rise) to their proper position in the array, similar to bubbles rising in a glass of soda. The bubble sort compares nearby array elements repeatedly. If the first and second items are out of order, they are compared and switched. The second and third items are then compared and, if out of order, swapped. This sorting procedure continues until the array's last two members are compared and, if out of order, then switched.

 

When the first pass over the array is finished, the bubble sort goes back to elements one and two and repeats the procedure. So, when does it come to a halt? When the bubble sort has examined the entire array and no "swaps" are required, it knows it is finished (thus the list is in proper order).

Before, during, and after a bubble sort for decreasing order, the table below shows an array of numbers. A "pass" is described as a complete loop across the array, comparing and swapping neighbouring elements as needed. Before the array can be sorted, it must be passed through several times.

 

Although the bubble sort is a simple method to code, it is slower than many other sorts. With a bubble sort, one final "pass" through the array is always required to confirm that no swaps are done and that the operation is complete. In reality, the procedure is complete before this final pass is performed.