Bubble Sort is a simple sorting algorithm that repeatedly steps through a list, compares adjacent elements, and swaps them if they are in the wrong order. This process is repeated until the list is fully sorted.
When to Use Bubble Sort
Best suited for small datasets or nearly sorted arrays due to its simplicity.
Not efficient for large datasets because of its O(n²) time complexity.
Time Complexity
Best case: O(n) – when the array is already sorted
Average case: O(n²)
Worst case: O(n²)
Example
Pass 1
Pass 2
Pass 3
Pass 4
Pass 5
Algorithm
void bubbleSort(array) {
int n = length of array
repeat i from 0 to n-1 {
boolean swapped = false
repeat j from 0 to n-i-1 {
if array[j] is greater than array[j+1] {
swap(array[j], array[j+1])
swapped = true
}
}
if not swapped:
break
}
return array
}
Optimizations
If no swaps occur during a pass, the array is already sorted, so the algorithm can terminate early.
In the inner loop, use
n - i - 1
instead ofn - 1
to avoid rechecking elements that are already sorted.
✅ Summary:
Bubble Sort is simple and intuitive, great for learning basic sorting concepts, but not suitable for large datasets due to its quadratic time complexity