Blog 7: Sorting Basics – Bubble Sort Explained Simply
Learn Bubble Sort with simple step-by-step examples and diagrams. Understand how adjacent elements are compared and swapped, why Bubble Sort is O(n²), and how optimization works. Build strong sorting fundamentals for coding interviews. #DSA #Sorting #BubbleSort #Algorithms #Programming #Coding #Tech
Introduction
So far, you’ve learned:
- Arrays
- Time & Space Complexity
- Searching (Linear vs Binary)
Now the next important question:
How do we arrange data in order?
This is called Sorting.
1) What is Sorting?
Sorting means:
Arranging elements in a specific order (ascending or descending)
Example
Before: [5, 3, 8, 2]
After (Ascending): [2, 3, 5, 8]
🔹 What is Bubble Sort?
Bubble Sort is the simplest sorting algorithm.
It compares adjacent elements and swaps them if they are in the wrong order.
👉 Larger elements “bubble up” to the end.
2) How Bubble Sort Works (Step-by-Step)
Let’s understand with an example:
[5, 3, 8, 2]
🔁 Pass 1
Compare 5 & 3 → swap → [3, 5, 8, 2]
Compare 5 & 8 → no swap → [3, 5, 8, 2]
Compare 8 & 2 → swap → [3, 5, 2, 8]
Result after Pass 1: [3, 5, 2, 8]
Largest element (8) is now at correct position ✅
🔁 Pass 2
Compare 3 & 5 → no swap → [3, 5, 2, 8]
Compare 5 & 2 → swap → [3, 2, 5, 8]
Result after Pass 2: [3, 2, 5, 8]
🔁 Pass 3
Compare 3 & 2 → swap → [2, 3, 5, 8]
Result after Pass 3: [2, 3, 5, 8] ✅ Sorted
Visual Understanding
Pass 1 → biggest element moves to end
Pass 2 → second biggest moves
Pass 3 → third biggest moves
Each pass → pushes largest remaining element to correct position
💻 Code (JavaScript)
function bubbleSort(arr) {
let n = arr.length;
for (let i = 0; i < n - 1; i++) {
for (let j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
// swap
let temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
return arr;
}
Bubble Sort Code Flow (Visual Diagram)
Start
↓
Take Array → [5, 3, 8, 2]
↓
Outer Loop (i = 0 → n-1)
↓
Inner Loop (j = 0 → n-i-1)
↓
Compare arr[j] & arr[j+1]
↓
Is arr[j] > arr[j+1] ?
↓ Yes ↓ No
Swap Elements Do Nothing
↓ ↓
[3, 5, 8, 2] Move Ahead
↓
Continue Inner Loop →
↓
End of Pass (largest element moves to end)
↓
Next Pass (i++)
↓
Repeat until sorted
↓
Return Sorted Array ✅
🔁 Pass-Level Understanding (Mapped with Flow)
Pass 1:
[5, 3, 8, 2]
→ swap → [3, 5, 8, 2]
→ no swap
→ swap → [3, 5, 2, 8]
Pass 2:
[3, 5, 2, 8]
→ no swap
→ swap → [3, 2, 5, 8]
Pass 3:
[3, 2, 5, 8]
→ swap → [2, 3, 5, 8]
🎯 Code → Visual Mapping
for (i) → controls number of passes
for (j) → controls comparisons
if condition → decision point
swap → action
⚡ Super Simple Mental Model
Compare → Swap → Move Forward → Repeat
After each pass → one element fixed
How Bubble Sort actually works inside the code?
🔹 Step 1: Function Setup
function bubbleSort(arr) {
let n = arr.length;
👉 We take an array as input
👉 n is the size of the array
🔹 Step 2: Outer Loop (Number of Passes)
for (let i = 0; i < n - 1; i++) {
👉 This loop controls how many passes we run
Why n - 1?
- For 4 elements → max 3 passes needed
- After each pass, one element is already sorted
👉 So we don’t need full n passes
🔹 Step 3: Inner Loop (Comparison)
for (let j = 0; j < n - i - 1; j++) {
👉 This loop compares adjacent elements
Why n - i - 1?
- After every pass, last elements are already sorted
- So we reduce comparisons
👉 This is the key optimization
🔹 Step 4: Comparison Logic
if (arr[j] > arr[j + 1]) {
👉 If current element is greater than next
👉 That means they are in the wrong order
🔹 Step 5: Swap
let temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
👉 Swap the two elements
Example:
[5, 3] → [3, 5]
🔹 Step 6: Return Result
return arr;
}
👉 Finally, return sorted array
Full Flow (Visual Mapping with Code)
Outer loop → number of passes
Inner loop → comparisons in each pass
if condition → checks order
swap → fixes order
🎯 Key Understanding
Outer loop decides how many rounds
Inner loop decides how many comparisons per round
⚡ One-Line Intuition
“Keep comparing neighbors and pushing the largest element to the end in every pass.”
💡 Small Upgrade (Optional — More Clean Swap)
You can also write swap like this:
[arr[j], arr[j + 1]] = [arr[j + 1], arr[j]];
3) ⏱ Time Complexity
- Worst Case: O(n²)
- Average Case: O(n²)
- Best Case: O(n) (if optimized)
4) 📦 Space Complexity
- O(1) → no extra memory used (in-place)
5) Why Bubble Sort is Slow ⚠️
It compares every pair again and again
Even if array is almost sorted
👉 Too many unnecessary comparisons
6) Interview Insight
👉 Interviewers may ask:
- Can you optimize it? (early exit if no swaps)
7) Optimized Bubble Sort (Important)
function bubbleSort(arr) {
let n = arr.length;
for (let i = 0; i < n - 1; i++) {
let swapped = false;
for (let j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
[arr[j], arr[j + 1]] = [arr[j + 1], arr[j]];
swapped = true;
}
}
if (!swapped) break; // already sorted
}
return arr;
}
8) Deep Understanding 🧠
⏱ Time Complexity (Deep but Simple)
🔹 Why Bubble Sort is O(n²)
Look at your code:
for (let i = 0; i < n - 1; i++) {
for (let j = 0; j < n - i - 1; j++) {
👉 Two loops = nested loops
Visual Thinking
Outer loop → runs ~ n times
Inner loop → runs ~ n times
Total work ≈ n × n = n²
More Intuitive View
n = 4
Pass 1 → 3 comparisons
Pass 2 → 2 comparisons
Pass 3 → 1 comparison
Total = 3 + 2 + 1 = 6 ≈ n²
Final Breakdown
🔸 Worst Case → O(n²)
👉 When array is completely unsorted
[5, 4, 3, 2, 1]
- Every comparison leads to swap
- Full nested loop runs
🔸 Average Case → O(n²)
👉 Random order
- Still many comparisons
- Still behaves like n²
🔸 Best Case → O(n) (Only if optimized)
👉 Already sorted array
[1, 2, 3, 4, 5]
If you use this optimization:
if (!swapped) break;
Then:
- First pass → no swaps
- Loop breaks early
👉 Only 1 pass → O(n)
⚡ Key Understanding
Without optimization → always O(n²)
With optimization → best case becomes O(n)
Space Complexity
🔹Why Bubble Sort is O(1) ?
Look at the code:
let temp = arr[j];
👉 Only one extra variable used
What is NOT happening
❌ No new array created
❌ No extra data structure
❌ No recursion stack
Visual Thinking
Input array → [5, 3, 8, 2]
Sorting happens inside same array
No extra memory grows with input
Final Answer
Space Complexity = O(1)
Because memory usage stays constant
Important Term
👉 This is called:
In-place sorting
Meaning:
- Modify original array
- No extra space required
⚡ One-Line Intuition
- Time Complexity → how many steps
- Space Complexity → how much extra memory
🔥 Super Simple Summary
Bubble Sort:
Time → O(n²) (nested loops)
Space → O(1) (no extra memory)
🧩 Quick Practice
👉 Sort this using Bubble Sort:
[4, 1, 3]
🚀 What’s Next?
Now that you understand basic sorting…
👉 Next blog:
“Selection Sort Explained Simply”
✍️ Closing Thought
“Bubble Sort is not about performance — it’s about understanding how sorting works.”