Bytes
rocket

Your Success, Our Mission!

6000+ Careers Transformed.

Step-by-Step Code Implementation

Last Updated: 2nd March, 2026

Implementing Bubble Sort in C

Understanding the step-by-step logic of passes and comparisons is the perfect foundation. Now, it's time to translate that theory into a functional program. In this section, we will walk through the practical implementation of the Bubble Sort algorithm using the C programming language. We'll see how its core principles—nested loops for iteration and conditional statements for swapping—come together to create a simple yet powerful sorting function. This hands-on C code example will solidify your understanding and show you exactly how the "bubbling" action is achieved in a real-world script.

4.1 : Step-by-Step Code Implementation

Let's build our Bubble Sort in C program from the ground up. The most logical way to do this is to create a dedicated function, let's call it bubbleSort(), that will contain all the sorting logic. To keep our code clean, we'll also make a small helper function, swap(), to exchange the values of two elements.

Here is the complete, commented C code:

#include <stdio.h> // A helper function to swap two integer values // We use pointers to modify the original array elements void swap(int *a, int *b) {    int temp = *a;    *a = *b;    *b = temp; } // The primary function to implement Bubble Sort void bubbleSort(int arr[], int n) {    int i, j;        // Outer loop: Controls the number of passes    // We need n-1 passes in the worst case    for (i = 0; i < n - 1; i++) {                // Inner loop: Performs the comparisons in each pass        // It runs from the start (j=0) to the beginning of the sorted portion        // The sorted portion is 'n - 1 - i'        for (j = 0; j < n - i - 1; j++) {                        // Compare the adjacent elements            if (arr[j] > arr[j + 1]) {                // If the element is larger than the next one, swap them                swap(&arr[j], &arr[j + 1]);            }        }    } } // A utility function to print the array void printArray(int arr[], int size) {    for (int i = 0; i < size; i++) {        printf("%d ", arr[i]);    }    printf("\n"); } // The main function to drive the program int main() {    int arr[] = {5, 1, 4, 2, 8}; // Our example array    int n = sizeof(arr) / sizeof(arr[0]); // Calculate the size of the array        printf("Unsorted array: \n");    printArray(arr, n);        // Call the bubbleSort function to sort the array    bubbleSort(arr, n);        printf("Sorted array: \n");    printArray(arr, n);        return 0; }

Output of this Program:

Unsorted array: 5 1 4 2 8 Sorted array: 1 2 4 5 8

This step-by-step code implementation clearly shows how to take an unsorted array, apply the bubbleSort function, and get a fully sorted array as the result.

4.1.1: Using Loops and Conditional Statements

The C implementation of Bubble Sort is a perfect example of how loops and conditional statements work together to solve a complex problem. Let's break down the logic of the bubbleSort function:

The Outer Loop (The "Passes"):

for (i = 0; i < n - 1; i++) { ... }

This for loop is responsible for controlling the passes. As we learned, for an array with n elements, the algorithm needs a maximum of n-1 passes to guarantee the array is sorted. The variable i acts as a counter for these passes. After the first pass (i=0), the largest element is at the end. After the second pass (i=1), the second-largest is in its place, and so on.

The Inner Loop (The "Comparisons"):

for (j = 0; j < n - i - 1; j++) { ... }

This nested for loop is the workhorse. It performs the actual adjacent comparisons within a single pass.

It starts at j = 0 (the beginning of the array).

It stops at n - i - 1. Why?

We subtract 1 because we are comparing arr[j] with arr[j+1]. The loop must stop one element before the end to prevent reading past the array's boundary.

We subtract i because after i passes, the last i elements are already sorted and in their final positions. We don't need to check them again, which is a small but important optimization.

The Conditional Statement (The "Swap Logic"):

if (arr[j] > arr[j + 1]) {    swap(&arr[j], &arr[j + 1]); }

This if statement is the "brain" of the operation. It checks if the current element (arr[j]) is greater than the one next to it (arr[j+1]). If this condition is true, it means the elements are in the wrong order (for an ascending sort). The code then enters the block and calls our swap() function to flip them. If the condition is false (the elements are already in order), the if block is skipped, and no swap occurs.

Together, these nested loops and the simple conditional check methodically bubble the largest elements to the end, pass by pass, until the entire array is sorted.

Module 3: Implementing Bubble Sort in CStep-by-Step Code Implementation

Top Tutorials

Related Articles