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!
Original Array: [5, 3, 1, 4]
#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.
Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!