![]() |
VOOZH | about |
Bubble Sort Algorithm is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. It is often used to introduce the concept of a sorting and is particularly suitable for sorting small datasets.
To sort a data set using bubble sort algorithm, follow the below steps:
This algorithm is for increasing order but with minor changes, it can be implemented for any desired order.
The below program sorts a vector using bubble sort:
1 2 4 5 8
We may notice in the above algorithm that if the inner loop does not cause any swap, the array is already sorted, but it will still run O(n2) time. This can be optimized by stopping the algorithm if the inner loop didn’t cause any swap. We can use a flag variable to indicate whether the swap happened or not.
1 2 4 5 8
Time Complexity: O(n2)
Space Complexity: O(1)