Bubble Sort Implementation Using a Single for
Loop in C
2 min readNov 25, 2024
I recently decided to revisit the Bubble Sort algorithm in C. Still, instead of using the typical nested loops, it would be interesting to challenge myself to implement it with just a single for
loop. It turned out to be a fun experiment! Here's the code I came up with, and I’d love to get some feedback on it. Maybe it could even help others curious about alternative ways to approach classic problems.
#include <stdio.h>
int main() {
int a[] = {22, 33, 55, 44, 11};
int n = sizeof(a) / sizeof(a[0]);
for (int i = 0; i < n - 1; i++) {
if (a[i] > a[i + 1]) {
int temp = a[i];
a[i] = a[i + 1];
a[i + 1] = temp;
}
if (i == n - 2) {
n--;
i = -1;
}
}
return 0;
}
Enhanced Code: Adding Print Statements for Clarity
To better understand how the array evolves after each iteration, I added print statements:
#include <stdio.h>
int main() {
int a[] = {22, 33, 55, 44, 11};
int n = sizeof(a) / sizeof(a[0]);
for (int i = 0; i < n - 1; i++) {
if (a[i] > a[i + 1]) {
int temp = a[i];
a[i] = a[i + 1];
a[i + 1] = temp;
}
printf("Array after iteration %d:\n", i + 1);
for (int j = 0; j < n; j++) {
printf(" %d", a[j]);
}
printf("\n");
if (i == n - 2) {
n--;
i = -1;
}
}
printf("Sorted Array\n");
for (int j = 0; j < sizeof(a) / sizeof(a[0]); j++) {
printf(" %d", a[j]);
}
return 0;
}
Output Example:
Here’s the output for the input array {22, 33, 55, 44, 11}
:
Array after iteration 1:
22 33 55 44 11
Array after iteration 2:
22 33 44 55 11
Array after iteration 3:
22 33 44 11 55
Array after iteration 4:
22 33 11 44 55
Array after iteration 5:
22 11 33 44 55
Array after iteration 6:
11 22 33 44 55
Sorted Array
11 22 33 44 55
This approach could be further optimized by introducing a flag to detect sorted arrays early and exit the loop.