Bubble sort

A visual walkthrough of the bubble sort algorithm

T he bubble sort algorithm is a sorting algorithm intended to sort data in ascending order. It’s generally thought of as an easy-to-understand algorithm, but it can be quite slow in comparison to other sorting algorithms.

How it works

Bubble sorting works on the basis of a pointer beginning at the first item in an array and comparing it to the item on its right. If the left item is greater than the right item, both items swap places.

The pointer then moves to the next index in the array, repeating the process above until the end of the array is reached.

At this point the last item in the array is the largest item in the array. The process is repeated until the array is sorted.

The highest unsorted value bubbles itself into the correct position - hence the name bubble sort.

7Index 0
6Index 1
5Index 2
1Index 3
4Index 4
3Index 5
2Index 6

Efficiency

The 2 steps involved when bubble sorting are comparing and swapping items. The comparisons are made between two items to determine which one is greater than the other and the swaps are made to swap the two items if the first item is greater than the second.

Overall the bubble sort algorithm is not that efficient in comparison to other sorting algorithms. The more items we have in the array, the more comparisons we need to make and the more swaps we need to make. The number of steps grows exponentially with the number of items in the array.

Conclusion

In general, for most practical applications and large datasets, more efficient sorting algorithms like merge sort, quicksort, or hybrid sorting algorithms are preferred over bubble sort but it can still be useful for the smaller data sets.