Bubble sort in C: solved exercise
If you searched for bubble sort in C solved exercise, this page explains the algorithm and its common optimization.
Problem statement
Sort an integer array ascending using bubble sort and stop early when no swaps happen.
C solution
#include <stdio.h>
void bubble_sort(int a[], int n) {
for (int i = 0; i < n - 1; i++) {
int swapped = 0;
for (int j = 0; j < n - 1 - i; j++) {
if (a[j] > a[j + 1]) {
int tmp = a[j];
a[j] = a[j + 1];
a[j + 1] = tmp;
swapped = 1;
}
}
if (!swapped) break;
}
}
int main(void) {
int a[] = {9, 3, 7, 1, 4};
int n = sizeof(a) / sizeof(a[0]);
bubble_sort(a, n);
for (int i = 0; i < n; i++) printf("%d ", a[i]);
printf("\n");
return 0;
}Expected output
1 3 4 7 9Complexity
- Worst case: O(n^2)
- Best case (optimized): O(n)
Common mistakes
- Not shrinking inner range with
- i. - Forgetting to reset swap flag.
- Confusing stability with speed.
Practical use
Not the fastest algorithm, but great for teaching, sanity checks, and tiny datasets.
Recommended next exercise
- Binary search in C: solved exercise on sorted arrays
- Merge sort in C: solved exercise with divide and conquer
- Strings in C: solved exercises with strlen, strcpy, and strcmp
- All C exercises
Guided practice and full book
If you want a complete path with progressive difficulty:
FAQ
Is this exercise useful for C exams and technical interviews?
Yes. It targets patterns that commonly appear in practice assignments, technical interviews, and C programming exams.
Where can I keep practicing with more solved C exercises?
In Programming in C in 100 Solved Exercises and C Exercises. Kindle Unlimited: View on Amazon.
How should I practice this exercise type to improve faster?
Start with small inputs, run edge cases (empty, one item, max capacity), then rewrite the solution from scratch without copying.