Bubble Sort Concept
- Ashok Kumar Kumawat
- Apr 25
- 2 min read
Bubble Sort repeatedly compares adjacent elements and swaps them if they are in the wrong order. After each pass, the largest element "bubbles up" to its correct position at the end.
C Code Example
#include <stdio.h>
int main() {
int arr[5] = {5, 3, 8, 4, 2}; // Example array
int i, j, temp;
int n = sizeof(array) / sizeof(array[0]);
printf("Original array: ");
for(i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
// Bubble Sort
for(i = 0; i < n-1; i++) {
for(j = 0; j < n-i-1; j++) {
if(arr[j] > arr[j+1]) {
// Swap
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
printf("\nSorted array: ");
for(i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
return 0;
}
Step-by-Step Example (Array: {5, 3, 8, 4, 2})
Pass 1:
Compare 5 and 3 → swap → {3, 5, 8, 4, 2}
Compare 5 and 8 → no swap
Compare 8 and 4 → swap → {3, 5, 4, 8, 2}
Compare 8 and 2 → swap → {3, 5, 4, 2, 8} 👉 Largest element (8) is now at the end.
Pass 2:
Compare 3 and 5 → no swap
Compare 5 and 4 → swap → {3, 4, 5, 2, 8}
Compare 5 and 2 → swap → {3, 4, 2, 5, 8} 👉 Second largest (5) is in place.
Pass 3:
Compare 3 and 4 → no swap
Compare 4 and 2 → swap → {3, 2, 4, 5, 8} 👉 Third largest (4) is in place.
Pass 4:
Compare 3 and 2 → swap → {2, 3, 4, 5, 8} 👉 Array is sorted!
Visual Representation (like images)
Think of each pass as bubbles rising:
Initial: [5, 3, 8, 4, 2]
After Pass 1: [3, 5, 4, 2, 8]
After Pass 2: [3, 4, 2, 5, 8]
After Pass 3: [3, 2, 4, 5, 8]
After Pass 4 (Final): [2, 3, 4, 5, 8]
Comments