Bubble Sort
β‘
AlgoDose Interactive Lab
Visualize Bubble Sort
Watch adjacent elements compare, swap, and bubble up into their sorted positions step-by-step.
Problem Statement:β
Given an arrayΒ arr, useΒ Bubble sortΒ to sort arr[] in increasing order.
-
Example:
Input:arr[] = [4, 1, 3, 9, 7]
Output:[1, 3, 4, 7, 9]
Explanation:Maintain sorted (in bold) and unsorted subarrays. Select 1. Array becomes1 4 3 9 7. Select 3. Array becomes1 3 4 9 7. Select 4. Array becomes1 3 4 9 7. Select 7. Array becomes1 3 4 7 9. Select 9. Array becomes1 3 4 7 9.
π Solution: Bubble Sortβ
class Solution {
public:
void bubbleSort(vector<int>& arr) {
int n = arr.size();
for(int i = n - 1; i >= 0; i--){
for(int j = 0; j < i; j++){
// Swap if the adjacent elements are in the wrong order
if(arr[j] > arr[j + 1]){
swap(arr[j], arr[j + 1]);
}
}
}
}
};
π How It Worksβ
- Bubble Sort works by repeatedly swapping adjacent elements if they are in the wrong order.
- After each pass, the largest unsorted element bubbles up to its correct position at the end.
- Outer loop runs from the end to the beginning.
- Inner loop compares adjacent pairs and swaps them if needed.
π§© Key Conceptβ
- Repeated adjacent comparison + swap
- Largest element "bubbles" to the end in each pass
β±οΈ Time & Space Complexityβ
| Best Case (Sorted) | O(nΒ²) (no break used here) |
|---|---|
| Average/Worst Case | O(nΒ²) |
| Space | O(1) (in-place) |
β οΈ Edge Casesβ
- Array of size
0or1β Already sorted - Already sorted array β Still does full O(nΒ²) unless optimized with a flag
- All elements same β No swaps needed
π‘ Other Approachesβ
| Algorithm | Time (Avg) | Stable | Notes |
|---|---|---|---|
| Selection Sort | O(nΒ²) | β | Picks min and swaps |
| Insertion Sort | O(nΒ²) | β | Good for small arrays |
| Merge Sort | O(n log n) | β | Divide & conquer |
| Quick Sort | O(n log n) | β | Fast, not stable |
| Heap Sort | O(n log n) | β | Uses heap, not stable |
π Related Problemsβ
- Sort Colors β LeetCode 75
- Merge Intervals
- Insertion Sort List β LeetCode 147
- Implement Sorting Algorithms
π¬