🚀 Learn BLE on Linux (BlueZ) – Programming Part 1
Hands-on Bluetooth Low Energy course. Special price: ₹399
Enroll Now on Udemy →Bubble Sort in C Explained
Trace every pass, count every swap, and write a bubble sort in C that stops early. Part of our free C programming course for embedded systems learners.
Bubble sort in C is the first sorting algorithm most students meet, and it is a perfect training ground for loops, array indexing and swapping. In this lecture of our free C programming course you will follow one small array through every pass, see exactly why the largest value “bubbles” to the right, and then write a clean, tested version that stops as soon as the data is sorted. If you are following this free embedded C course to prepare for firmware work, you will also see a real use of bubble sort: a median filter for noisy sensor readings.
What You Will Learn
- How bubble sort in C compares neighbours and swaps them
- Why pass number
konly needsN - kcomparisons - How to trace a bubble sort by hand using a pass table
- How an early-exit flag makes bubble sort fast on sorted data
- Best, average and worst case cost of bubble sort
- A real embedded C use: median of 5 ADC samples
- Common mistakes and how to debug them
Prerequisites
- One-dimensional arrays: declaring, indexing and looping over them (earlier lectures in this arrays chapter)
forloops and theifstatement- A C compiler such as
gccon Linux, or any embedded toolchain you already use
What Is Bubble Sort in C?
Bubble sort repeatedly walks through an array and looks at each pair of neighbouring elements. If the left element is larger than the right element, the two are swapped. After one complete walk (one pass), the largest value has been carried all the way to the last position, like an air bubble rising to the surface of water. The next pass does the same job for the remaining unsorted part, and so on, until nothing is left to fix.
The one-line idea
After pass 1 the biggest value is in its final place. After pass 2 the second biggest is in its final place. After pass k, the last k positions are final, so the next pass can ignore them.
Bubble Sort Pass by Pass
Let us sort six temperature-sensor readings: 52 17 38 9 44 26. Pass 1 compares five pairs, because six elements have five neighbouring pairs. Watch the value 52 travel to the right edge, swapping each time.
The same idea repeats on the shorter unsorted part. The table below records the whole run so you can check your own hand trace later.
| Pass | Comparisons | Swaps | Array after the pass |
|---|---|---|---|
| Start | – | – | 52 17 38 9 44 26 |
| 1 | 5 | 5 | 17 38 9 44 26 | 52 |
| 2 | 4 | 2 | 17 9 38 26 | 44 52 |
| 3 | 3 | 2 | 9 17 26 | 38 44 52 |
| 4 | 2 | 0 | 9 17 26 38 44 52 (no swap, stop) |
Notice two facts. First, the number of comparisons shrinks by one each pass (5, 4, 3, 2). Second, pass 4 made zero swaps. A pass with zero swaps proves the array is already in order, so continuing would waste time. That observation leads directly to the early-exit flag.
Bubble Sort in C: Complete Program
The program below sorts the same six readings and prints the array after every pass. It uses a swapped flag to stop early. Type it in yourself rather than pasting, because typing builds the loop bounds into your memory.
#include <stdio.h>
#define COUNT 6
static void print_array(const int a[], int n)
{
for (int i = 0; i < n; i++)
printf("%3d", a[i]);
printf("\n");
}
int main(void)
{
int readings[COUNT] = {52, 17, 38, 9, 44, 26};
int total_swaps = 0;
printf("Start :");
print_array(readings, COUNT);
for (int pass = 1; pass < COUNT; pass++) {
int swapped = 0;
for (int j = 0; j < COUNT - pass; j++) {
if (readings[j] > readings[j + 1]) {
int tmp = readings[j];
readings[j] = readings[j + 1];
readings[j + 1] = tmp;
swapped = 1;
total_swaps++;
}
}
printf("After P%d :", pass);
print_array(readings, COUNT);
if (!swapped) {
printf("No swap in pass %d, stopping early\n", pass);
break;
}
}
printf("Total swaps: %d\n", total_swaps);
return 0;
}
How the code works
COUNTis a macro so the array size lives in exactly one place.- The outer loop runs
passfrom 1 toCOUNT - 1. An array of N items needs at most N – 1 passes. - The inner loop runs
jfrom 0 toCOUNT - pass - 1. Because the lastpass - 1items are already final, the inner loop skips them. - The comparison uses
readings[j + 1], sojmust stop one before the end. That is why the bound isCOUNT - passand the test isj < COUNT - pass. - The three-line swap uses a temporary variable
tmp. Without it, one value would be overwritten and lost. swappedis reset to 0 at the start of every pass and set to 1 whenever a swap happens.
Build and run
gcc -Wall -Wextra -std=c11 -o bubble_sort_trace bubble_sort_trace.c
./bubble_sort_trace
Expected output:
Start : 52 17 38 9 44 26
After P1 : 17 38 9 44 26 52
After P2 : 17 9 38 26 44 52
After P3 : 9 17 26 38 44 52
After P4 : 9 17 26 38 44 52
No swap in pass 4, stopping early
Total swaps: 9
The output matches the pass table: 9 swaps in total (5 + 2 + 2 + 0), and the program stops after pass 4 even though the loop allowed up to pass 5.
Why the Early Exit Matters
Without the flag, bubble sort in C always performs N(N-1)/2 comparisons, even for data that is already sorted. With the flag, an already-sorted array needs just one pass of N-1 comparisons and then stops.
| Input state | Passes (with flag) | Comparisons | Swaps |
|---|---|---|---|
| Already sorted (best case) | 1 | N – 1 | 0 |
| Random order (average) | about N | up to N(N-1)/2 | about half the comparisons |
| Reverse sorted (worst case) | N – 1 | N(N-1)/2 | N(N-1)/2 |
Key point
Time complexity of bubble sort: O(N) in the best case (with the early-exit flag), O(N squared) in the average and worst cases. Extra memory: O(1), because it sorts in place using one temporary variable.
Real Embedded C Use: Median of 5 Samples
You will rarely sort thousands of items with bubble sort on a microcontroller, but sorting a handful of values is common. A classic job is filtering noise from an ADC: take five samples, sort them, and use the middle one. A single spike cannot move the median. Because the window is only five samples, the simple bubble sort is small, predictable and uses almost no RAM, which is exactly what firmware wants.
#include <stdio.h>
#define WINDOW 5
/* Median of 5 ADC samples using a tiny bubble sort on a private copy. */
static int median_of_five(const int samples[WINDOW])
{
int tmp[WINDOW];
for (int i = 0; i < WINDOW; i++)
tmp[i] = samples[i];
for (int pass = 1; pass < WINDOW; pass++) {
int swapped = 0;
for (int j = 0; j < WINDOW - pass; j++) {
if (tmp[j] > tmp[j + 1]) {
int t = tmp[j];
tmp[j] = tmp[j + 1];
tmp[j + 1] = t;
swapped = 1;
}
}
if (!swapped)
break;
}
return tmp[WINDOW / 2];
}
int main(void)
{
int adc[WINDOW] = {512, 498, 1023, 505, 510}; /* 1023 is a noise spike */
printf("Raw samples : %d %d %d %d %d\n",
adc[0], adc[1], adc[2], adc[3], adc[4]);
printf("Median : %d\n", median_of_five(adc));
return 0;
}
gcc -Wall -Wextra -std=c11 -o median_filter median_filter.c
./median_filter
Raw samples : 512 498 1023 505 510
Median : 510
The spike value 1023 is ignored completely. Notice that the function copies the samples into tmp first, so the caller’s original data stays in arrival order. Also notice const on the parameter: it tells the compiler and the reader that this function only reads the original array.
Common Mistakes in Bubble Sort in C
| Mistake | What happens | Fix |
|---|---|---|
Inner loop runs to j < COUNT | Reads arr[COUNT], one past the end (undefined behaviour) | Use j < COUNT - pass so j + 1 stays valid |
Swap written as a = b; b = a; | Both elements end up equal; data lost | Save one value in a temporary first |
Using >= in the comparison | Equal items are swapped for no reason; sort is no longer stable | Swap only when strictly greater |
swapped declared outside the pass loop and never reset | Early exit never triggers | Reset it to 0 at the start of each pass |
| Sorting the caller’s original buffer by accident | Arrival order of samples is lost | Sort a copy when order matters |
Warning: An off-by-one in the inner loop bound rarely crashes a desktop program, so the bug can hide for months. On a microcontroller, reading past the array can quietly pick up a neighbouring variable. Always ask: “what is the largest index my code touches?”
Debugging Tips
- Print the array after every pass, exactly as the example program does.
- Check the pass number against the comparison count: pass 1 must make N – 1 comparisons.
- Test three arrays: already sorted, reverse sorted, and one with duplicate values.
- Compile with
-Wall -Wextra. Add-fsanitize=address,undefinedon your PC to catch out-of-bounds reads.
Best Practices
- Keep the array size in a macro or a
constand pass the length to any sorting function. - Wrap the sort in a function so it can be tested alone.
- Use bubble sort only for small arrays (roughly a few dozen items). For larger data use the standard library
qsortor a better algorithm. - Remember it is stable: equal values keep their original relative order, which matters when sorting records by one field.
- Performance: the worst case does about N(N-1)/2 swaps, and each swap writes memory. On flash-backed or slow memory this cost is noticeable.
Summary and Key Takeaways
- Bubble sort compares neighbours and swaps them when the left one is bigger.
- After pass k, the last k elements are in their final positions.
- The inner loop bound
COUNT - passavoids both wasted work and out-of-range access. - A
swappedflag gives O(N) best-case time on sorted input. - Worst-case time is O(N squared); memory use is O(1); the sort is stable.
- Small fixed-size windows, such as a 5-sample median filter, are a legitimate embedded use.
Conclusion
You now understand bubble sort in C well enough to trace it on paper, write it from memory, and explain its cost. The same skills (nested loops, safe index bounds, a temporary variable for swapping) appear in every later algorithm in this free C programming course. In the next lecture you will learn how to insert a new element into an array that is already sorted, which is the building block of insertion sort.
Frequently Asked Questions
Why is it called bubble sort?
Large values move to the end of the array one swap at a time, much like bubbles rising through liquid.
How many passes does bubble sort in C need?
At most N – 1 passes for N elements. With an early-exit flag it can finish sooner, and on an already-sorted array it needs only one pass.
Is bubble sort stable?
Yes, as long as you swap only when the left element is strictly greater than the right one.
What is the time complexity of bubble sort?
O(N) in the best case with an early-exit flag, and O(N squared) in the average and worst cases.
Should I use bubble sort in embedded C projects?
Only for very small arrays, such as median filters over 3 to 9 samples. For larger arrays prefer qsort or an algorithm with better growth.
Why do we use COUNT – pass as the inner loop limit?
After each pass the largest remaining value is fixed at the end, so the loop can skip those positions, and it also keeps j + 1 inside the array.
Can bubble sort sort in descending order?
Yes. Change the comparison from > to < and the largest values collect at the front instead.
Where can I learn more in this free embedded C course?
Continue with the next lectures in this arrays chapter: inserting into a sorted array, insertion sort, and merging sorted arrays.
Keep Learning with the Free Embedded C Course
EmbeddedPathashala offers a free C tutorial series, a free embedded systems course and a free Linux device drivers course, all written for students.

2 Comments