Bubble Sort Program In C Language

7 min read

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:

  1. Compare 5 and 3; swap them: 3 5 8 4 2
  2. Compare 5 and 8; leave them unchanged
  3. Compare 8 and 4; swap them: 3 5 4 8 2
  4. Compare 8 and 2; 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

  1. Input phase: The program first asks the user for the number of elements and then reads each integer into the array arr.
  2. Display original: Before sorting, printArray shows the unsorted data so the user can see what was entered.
  3. Sorting phase: bubbleSort performs the nested-loop comparison and swapping logic described earlier. The swapped flag acts as an optimization—if no swaps occur during a full pass, the array is already sorted and the function exits early.
  4. 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 - i instead of j < n - i - 1 causes an out-of-bounds access on arr[j + 1] during the last iteration of the inner loop.
  • Forgetting the swapped optimization: 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 a temp variable (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:

  1. 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.
  2. 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.
  3. Detecting a sorted state: If you need to check if a dataset is sorted while sorting it, the swapped flag gives you that answer for free in $O(n)$ best-case time.
  4. 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:

  1. Descending Order: Change the comparison so the largest elements sink to the bottom (or simply flip the > to <).
  2. Count Operations: Add global counters for comparisons and swaps. Print them after sorting to see how the swapped flag affects the counts for sorted vs. reverse-sorted input.
  3. Sort Strings: Adapt the function to accept char *arr[] and use strcmp for comparisons, implementing the generic callback approach mentioned earlier.
  4. 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.

More to Read

Just Published

Worth the Next Click

Still Curious?

Thank you for reading about Bubble Sort Program In C Language. We hope the information has been useful. Feel free to contact us if you have any questions. See you next time — don't forget to bookmark!
⌂ Back to Home