C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

Data Structures in C

Bubble Sort

Concept Overview

Bubble Sort is a comparison-based sorting algorithm that repeatedly steps through the array, compares adjacent elements, and swaps them if they are in the wrong order.

This process continues until the array is completely sorted.

How It Works (Step-by-Step)

Let’s say we have an array:

[5, 3, 8, 4, 2]

Pass 1:
Compare each adjacent pair and swap if needed:
→ [3, 5, 4, 2, 8]
Largest element (8) “bubbles up” to the end.

Pass 2:
→ [3, 4, 2, 5, 8]

Pass 3:
→ [3, 2, 4, 5, 8]

Pass 4:
→ [2, 3, 4, 5, 8]  → Sorted!

 

C Program: Bubble Sort

C

#include <stdio.h>

 

// Function to perform Bubble Sort

void bubbleSort(int arr[], int n) {

    int i, j, temp;

    int swapped;

 

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

        swapped = 0; // Flag to optimize the algorithm

 

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

            if (arr[j] > arr[j + 1]) {

                // Swap elements

                temp = arr[j];

                arr[j] = arr[j + 1];

                arr[j + 1] = temp;

                swapped = 1;

            }

        }

 

        // If no swaps occurred, the array is already sorted

        if (swapped == 0)

            break;

    }

}

 

// Function to print array

void printArray(int arr[], int n) {

    for (int i = 0; i < n; i++)

        printf("%d ", arr[i]);

    printf("\n");

}

 

int main() {

    int n;

    printf("Enter number of elements: ");

    scanf("%d", &n);

 

    int arr[n];

    printf("Enter %d elements:\n", n);

    for (int i = 0; i < n; i++)

        scanf("%d", &arr[i]);

 

    printf("Original array: ");

    printArray(arr, n);

 

    bubbleSort(arr, n);

 

    printf("Sorted array: ");

    printArray(arr, n);

 

    return 0;

}

Output

 
INPUT :
Enter number of elements: 5
Enter 5 elements:
5 3 8 4 2

OUTPUT :
Original array: 5 3 8 4 2 
Sorted array: 2 3 4 5 8

Algorithm Summary

Step

Description

1

Compare adjacent elements.

2

Swap them if they’re in the wrong order.

3

Repeat until the array is sorted.

4

Largest element “bubbles up” each pass.

Time and Space Complexity

Case

Time Complexity

Space

Best Case (Already sorted)

O(n)

 

Average Case

O(n²)

 

Worst Case

O(n²)

 

Space Complexity

O(1)

 

Optimized version (using swapped flag) stops early if no swaps occur → saves time when data is nearly sorted.

Key Takeaway Points

  • Simple and easy to implement.
  • Not efficient for large datasets.
  • Good for understanding sorting fundamentals.
  • Works in-place (no extra space needed).
  • Can be made stable — relative order of equal elements is maintained.