Skip to main content

Bubble Sort

⚑
AlgoDose Interactive Lab

Visualize Bubble Sort

Watch adjacent elements compare, swap, and bubble up into their sorted positions step-by-step.

▢ Open Visualizer→

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 CaseO(nΒ²)
SpaceO(1) (in-place)

⚠️ Edge Cases​

  • Array of size 0 or 1 β†’ Already sorted
  • Already sorted array β†’ Still does full O(nΒ²) unless optimized with a flag
  • All elements same β†’ No swaps needed

πŸ’‘ Other Approaches​

AlgorithmTime (Avg)StableNotes
Selection SortO(n²)❌Picks min and swaps
Insertion SortO(nΒ²)βœ…Good for small arrays
Merge SortO(n log n)βœ…Divide & conquer
Quick SortO(n log n)❌Fast, not stable
Heap SortO(n log n)❌Uses heap, not stable

  • Sort Colors – LeetCode 75
  • Merge Intervals
  • Insertion Sort List – LeetCode 147
  • Implement Sorting Algorithms

πŸ’¬

Discussion & Doubts