Bubble Sort is a simple sorting algorithm that repeatedly compares adjacent elements and swaps them if they are in the wrong order.
Large elements “bubble up” to the end of the list, like bubbles in water — hence the name.
📌 Definition
Bubble Sort is a comparison-based sorting algorithm in which adjacent elements are repeatedly swapped if they are in the wrong order until the array becomes sorted.
🧠 How Bubble Sort Works
Steps:
Compare first two elements
Swap if left > right
Move one position ahead
Repeat for entire array
After each pass, largest element moves to the end
Repeat until sorted
📊 Example
Unsorted Array:
A = [5, 1, 4, 2, 8]
🔁 Pass 1
Comparison
Action
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
👉 Largest (8) is in correct position
🔁 Pass 2
Comparison
Action
1 < 4
No swap
4 > 2
Swap → [1, 2, 4, 5, 8]
4 < 5
No swap
🔁 Pass 3
No swaps needed → array already sorted
📌 Final Sorted Array
[1, 2, 4, 5, 8]
💻 Algorithm (Pseudocode)
BubbleSort(A, n)
1. for i = 0 to n-1 2. for j = 0 to n-i-2 3. if A[j] > A[j+1] 4. swap(A[j], A[j+1])