DSA Tutorial



BUBBLE SORT IN DSA


šŸ” Bubble Sort in DSA

Bubble Sort is one of the simplest sorting algorithms. It repeatedly steps through the list, compares adjacent elements and swaps them if they are in the wrong order.

🧠 Imagine bubbles rising in water — smaller bubbles "bubble up" to the top by swapping with larger ones!

āš™ļø How It Works

  • Compare adjacent elements
  • If the left element is greater, swap them
  • Repeat for the entire array, multiple times

šŸ” Example

Original Array: [5, 3, 1, 4]

  • Compare 5 and 3 → Swap → [3, 5, 1, 4]
  • Compare 5 and 1 → Swap → [3, 1, 5, 4]
  • Compare 5 and 4 → Swap → [3, 1, 4, 5]
  • Repeat the process again until sorted → [1, 3, 4, 5]

šŸ’» C Code Example

#include <stdio.h>

void bubbleSort(int arr[], int n) {
    for (int i = 0; i < n-1; i++) {
        for (int j = 0; j < n-i-1; j++) {
            if (arr[j] > arr[j+1]) {
                // swap
                int temp = arr[j];
                arr[j] = arr[j+1];
                arr[j+1] = temp;
            }
        }
    }
}

int main() {
    int a[] = {5, 3, 1, 4};
    int n = 4;
    bubbleSort(a, n);
    for (int i = 0; i < n; i++) {
        printf("%d ", a[i]);
    }
    return 0;
}
    

ā±ļø Time Complexity: O(n²) in worst and average case
āœ… Best Case: O(n) (when array is already sorted)
šŸ” Stable: Yes

šŸ’” Use Bubble Sort only for small datasets or learning purposes. It's not efficient for large data.


🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review