Sorting Algorithm — Bubble Sort

Justgiveacar
2 min readFeb 15, 2021

Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in wrong order. The pass through the list is repeated until the list is sorted. The algorithm, which is a comparison sort.

Bubble sort has a worst-case and average complexity of O(n²), where n is the number pf items being sorted.

How Bubble Sort Works ?

  1. Starting from the first index, compare the first and the second elements. If the first element is greater than the second, they are swapped. And we keep comparing the second and the third elements, swap them if they are not in order.

2. The same process goes on for the remaining iterations except for the last number which is the largest number right now by previous sorting process. After each iteration, the largest element among the unsorted elements is placed at the end. In each iteration, the comparison takes place up to the last unsorted element. The array is sorted when all the unsorted elements are placed at their correct positions.

Let’s take a look at the Java Code

Actually, in the above code, all possible comparisons are made even if the array is already sorted. It increases the execution time. We can add an extra variable swapped. After each iteration, if there is no swapping taking place then, there is no need for performing further loops.

Alright, that’s pretty much it.

Thanks for reading my article. If you like it, please give me a small 👏. Appreciate ❤️

--

--