DSA Bubble Sort

DSA Tutorial

DSA Bubble Sort – Beginner Friendly Guide

Bubble Sort is one of the simplest sorting algorithms in Data Structures & Algorithms (DSA).
It is mainly used for learning purposes and to understand how sorting works step by step.

DSA Bubble Sort

1️⃣ Bubble Sort – Manual Run Through (Step-by-Step) ⭐⭐⭐

🔹 Given Array

[5, 1, 4, 2, 8]

Bubble Sort compares adjacent elements and swaps them if they are in the wrong order.


🔸 Pass 1

Compare till the end (largest bubbles up)

(5,1) → swap → [1,5,4,2,8]
(5,4) → swap → [1,4,5,2,8]
(5,2) → swap → [1,4,2,5,8]
(5,8) → no swap → [1,4,2,5,8]

✅ After Pass 1 → 8 is in correct position


🔸 Pass 2

Ignore last element (already sorted)

(1,4) → no swap → [1,4,2,5,8]
(4,2) → swap → [1,2,4,5,8]
(4,5) → no swap → [1,2,4,5,8]

✅ After Pass 2 → 5 is in correct position


🔸 Pass 3

(1,2) → no swap
(2,4) → no swap

No swaps → array already sorted
🛑 Algorithm stops (optimized version)


✅ Final Sorted Array

[1, 2, 4, 5, 8]

2️⃣ Bubble Sort Algorithm (Logic) ⭐⭐

Basic Idea

  • Repeat comparisons

  • Swap adjacent elements if needed

  • After each pass, largest element goes to the end


3️⃣ Bubble Sort Implementation (C++) ⭐⭐

🔹 Basic Bubble Sort


 

Output

1 2 4 5 8

4️⃣ Optimized Bubble Sort Implementation ⭐⭐⭐

Stops early if no swaps occur in a pass.


 

📌 Important for exams & interviews


5️⃣ Bubble Sort Time Complexity ⭐⭐⭐

🔹 Comparisons Count

(n-1) + (n-2) + (n-3) + ... + 1
= n(n-1)/2

⏱ Time Complexity Table

CaseConditionTime Complexity
Best CaseAlready sorted (optimized)O(n)
Average CaseRandom orderO(n²)
Worst CaseReverse sortedO(n²)

🧠 Why Worst Case is O(n²)?

  • Two nested loops

  • Each element compared multiple times


6️⃣ Space Complexity ⭐⭐

MetricValue
Extra SpaceO(1)
TypeIn-place sorting

📌 Bubble Sort does not use extra memory


7️⃣ Important Properties (Exam Gold ⭐⭐⭐)

✔ Stable sorting algorithm
✔ In-place algorithm
✔ Comparison-based
✔ Not suitable for large datasets


8️⃣ Common Interview Questions ❓

Q1. Why is Bubble Sort called Bubble Sort?
👉 Largest element bubbles to the end

Q2. Is Bubble Sort stable?
👉 Yes

Q3. Can Bubble Sort be optimized?
👉 Yes, using swap flag

Q4. Why Bubble Sort is not used in practice?
👉 O(n²) time complexity


✅ Final Summary

✔ Bubble Sort swaps adjacent elements
✔ Largest element moves to end each pass
✔ Easy to understand & implement
✔ Optimized version stops early
✔ Time Complexity: O(n²)
✔ Space Complexity: O(1)
✔ Best for learning, not for production

You may also like...