📅 Date: Jan 16, 2026
🔥 Topic: Sorting Part 1: Bubble Sort


🫧 The Logic

Bubble Sort is the simplest sorting algorithm.
Idea: Compare two adjacent elements. If the left one is bigger, swap them. Repeat this until the largest element "bubbles up" to the end (or sinks to the bottom).

📊 Dry Run Table (Visualizing the Flow)

Let's sort: [5, 1, 4, 2, 8]

Pass Comparisons & Swaps Array State
1 Swap (5,1), Swap (5,4), Swap (5,2), No Swap (5,8) [1, 4, 2, 5, 8]
2 No Swap (1,4), Swap (4,2), No Swap (4,5) [1, 2, 4, 5, 8]
3 No Swap (1,2), No Swap (2,4) [1, 2, 4, 5, 8]

Notice: The largest elements get fixed at the end one by one.

💻 The Code (O(n²))

#include <iostream>
using namespace std;

int main() {
    int arr[] = {5, 1, 4, 2, 8};
    int n = 5;

    // Outer loop for passes
    for(int i = 0; i < n-1; i++) {
        // Inner loop for comparison
        for(int j = 0; j < n-i-1; j++) {
            
            if(arr[j] > arr[j+1]) {
                // Swap Logic
                int temp = arr[j];
                arr[j] = arr[j+1];
                arr[j+1] = temp;
            }
        }
    }

    // Print Sorted
    for(int i=0; i<n; i++) cout << arr[i] << " ";
    return 0;
}

💭 Thoughts

It's easy to code but not efficient for large data. The logic is: "Push the heaviest element to the right corner."