A bubble sort program in C language arranges a list of values by repeatedly comparing neighboring elements and swapping them when they are in the wrong order. Although bubble sort is rarely the fastest choice for large datasets, it is an excellent way to learn loops, arrays, conditionals, and algorithmic thinking in C.
Introduction
Sorting means organizing data according to a specific rule, such as arranging numbers from smallest to largest. Bubble sort gets its name from the way larger values gradually move—or “bubble”—toward the end of an array during each pass.
The algorithm is:
- Simple to understand and implement
- An in-place sorting algorithm because it rearranges elements inside the original array
- Stable when equal elements are never swapped
- Most useful for education, small datasets, and data that is already nearly sorted
How Bubble Sort Works
Bubble sort compares two adjacent elements at a time. In practice, for ascending order, it checks whether the element on the left is greater than the element on the right. If it is, the two values are exchanged.
Consider this array:
5 3 8 4 2
During the first pass:
- Compare
5and3; swap them:3 5 8 4 2 - Compare
5and8; leave them unchanged - Compare
8and4; swap them:3 5 4 8 2 - Compare
8and2; swap them:3 5 4 2 8
The largest value, 8, is now in its correct final position. The next pass repeats the process while ignoring that sorted final position. After enough passes, the complete array becomes:
2 3 4 5 8
Complete Bubble Sort Program in C
#include
void bubbleSort(int arr[], int n)
{
int i, j, temp;
int swapped;
for (i = 0; i < n - 1; i++)
{
swapped = 0;
for (j = 0; j < n - i - 1; j++)
{
if (arr[j] > arr[j + 1])
{
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
swapped = 1;
}
}
if (swapped == 0)
{
break;
}
}
}
void printArray(int arr[], int n)
{
int i;
for (i = 0; i < n; i++)
{
printf("%d", arr[i]);
if (i < n - 1)
{
printf(" ");
}
}
printf("\n");
}
int main(void)
{
int arr[100];
int n, i;
printf("Enter the number of elements: ");
if (scanf("%d", &n) !=
```c
if (scanf("%d", &n) != 1 || n <= 0 || n > 100)
{
printf("Invalid input.\n");
return 1;
}
printf("Enter %d integers:\n", n);
for (i = 0; i < n; i++)
{
if (scanf("%d", &arr[i]) != 1)
{
printf("Invalid input.\n");
return 1;
}
}
printf("Original array: ");
printArray(arr, n);
bubbleSort(arr, n);
printf("Sorted array: ");
printArray(arr, n);
return 0;
}
How the Program Works Step by Step
- Input phase: The program first asks the user for the number of elements and then reads each integer into the array
arr. - Display original: Before sorting,
printArrayshows the unsorted data so the user can see what was entered. - Sorting phase:
bubbleSortperforms the nested-loop comparison and swapping logic described earlier. Theswappedflag acts as an optimization—if no swaps occur during a full pass, the array is already sorted and the function exits early. - Output phase: After sorting, the program prints the final sorted array.
Understanding the Complexity
| Case | Time Complexity |
|---|---|
| Best | O(n) — when the array is already sorted and the swapped flag triggers an early exit |
| Average | O(n²) — elements are in random order |
| Worst | O(n²) — when the array is sorted in reverse order |
People argue about this. Here's where I land on it Turns out it matters..
The space complexity is O(1) because bubble sort only uses a fixed number of extra variables (temp, swapped, i, j) regardless of the input size.
Possible Improvements
- Bidirectional bubble sort (Cocktail shaker sort): Instead of sweeping left-to-right every pass, alternate directions. This helps when small values are trapped near the end of the array ("turtles").
- Tracking the last swap position: Record the index of the last swap in each pass. All elements beyond that index are already sorted, so the next pass can ignore them entirely.
- Generic implementation: Use
void*pointers and a comparison function callback so the same routine can sort strings, floating-point numbers, or custom structures.
Conclusion
The bubble sort program in C serves as a foundational stepping stone for anyone learning programming. Its straightforward logic makes it the ideal first sorting algorithm to study, and the implementation reinforces core C concepts such as arrays, loops, conditionals, and function design. While more advanced algorithms like quicksort or mergesort outperform bubble sort on large datasets, mastering bubble sort builds the intuition needed to understand how comparison-based sorting works at a fundamental level. Whether you are a student preparing for exams, a beginner writing your first sorting routine, or an experienced developer revisiting classic algorithms, bubble sort remains a valuable and educational tool worth knowing inside and out Surprisingly effective..
Common Pitfalls to Avoid
Even with a simple algorithm like bubble sort, several subtle bugs frequently appear in student code:
- Off-by-one errors in loop bounds: Writing
j < n - iinstead ofj < n - i - 1causes an out-of-bounds access onarr[j + 1]during the last iteration of the inner loop. - Forgetting the
swappedoptimization: Without it, the algorithm always runs $O(n^2)$ steps even on pre-sorted data, missing the single best-case scenario where bubble sort shines. - Incorrect swap logic: Writing
arr[j] = arr[j + 1]; arr[j + 1] = arr[j];without a temporary variable overwrites the first value before it can be moved. Always use atempvariable (or XOR swap, though that is rarely preferred in modern C). - Using the wrong comparison operator: Using
>sorts ascending; using<sorts descending. Mixing them up produces the reverse of the intended order.
When to Actually Use Bubble Sort
Despite its $O(n^2)$ reputation, bubble sort has legitimate niche uses:
- Tiny or nearly sorted datasets: For arrays of fewer than ~50 elements, the low overhead (no recursion, no auxiliary stack, minimal branching) often makes it faster than quicksort or mergesort.
- Embedded systems with severe constraints: When RAM is measured in bytes and stack space is non-existent, bubble sort’s $O(1)$ space and tiny code footprint are decisive advantages.
- Detecting a sorted state: If you need to check if a dataset is sorted while sorting it, the
swappedflag gives you that answer for free in $O(n)$ best-case time. - Educational instrumentation: Because every comparison and swap is explicit, it is the easiest algorithm to visualize, instrument with counters, or animate for teaching purposes.
Exercises for the Reader
To solidify your understanding, try modifying the program to accomplish the following:
- Descending Order: Change the comparison so the largest elements sink to the bottom (or simply flip the
>to<). - Count Operations: Add global counters for
comparisonsandswaps. Print them after sorting to see how theswappedflag affects the counts for sorted vs. reverse-sorted input. - Sort Strings: Adapt the function to accept
char *arr[]and usestrcmpfor comparisons, implementing the generic callback approach mentioned earlier. - Implement Cocktail Shaker Sort: Rewrite the sorting function to sweep left-to-right, then right-to-left, updating the start and end bounds after each pass.
Final Word
Bubble sort is rarely the right tool for production code handling significant data volumes, but it is almost always the right tool for building a mental model of how sorting works. Plus, by tracing every comparison, every swap, and every pass boundary, you develop an intuition for invariants, loop termination, and algorithmic efficiency that transfers directly to understanding quicksort, heapsort, and beyond. Keep this implementation in your toolkit—not for deployment, but for the clarity it brings to the fundamentals of computer science.