C Program to Sort an Array Using Bubble Sort — With Optimisation and Complexity

Bubble Sort is the simplest sorting algorithm to understand and implement. It works by repeatedly comparing adjacent elements and swapping them if they are in the wrong order. After each pass, the largest unsorted element has “bubbled up” to its correct position at the end — just like air bubbles rising to the surface of water.

Bubble Sort is rarely used in production due to its O(n²) average performance, but it is an essential algorithm to know: it introduces the core idea of comparison-and-swap sorting, and its optimised version runs in O(n) on already-sorted input.

Algorithm — How It Works

  1. Compare arr[j] and arr[j+1] for every adjacent pair
  2. If arr[j] > arr[j+1], swap them
  3. After each full pass, the largest remaining element is in its final position
  4. Optimisation: if a full pass makes no swaps, the array is already sorted — stop early

Step-by-Step Example

Sort [64, 34, 25, 12, 22]:

Pass 1:  64>34 swap → 34>25 swap → 25>12 swap → 25>22 swap
         [34, 25, 12, 22, 64]    64 is in final position ✓

Pass 2:  34>25 swap → 34>12 swap → 34>22 swap
         [25, 12, 22, 34, 64]    34 is in final position ✓

Pass 3:  25>12 swap → 25>22 swap
         [12, 22, 25, 34, 64]    25 is in final position ✓

Pass 4:  12<22 → no swap  (swapped flag stays 0 → early exit)

Final:   [12, 22, 25, 34, 64] ✓

C Program — Bubble Sort

#include <stdio.h>

void swap(int *a, int *b) {
    int temp = *a;
    *a = *b;
    *b = temp;
}

void bubble_sort(int arr[], int n) {
    for (int i = 0; i < n - 1; i++) {
        int swapped = 0;

        for (int j = 0; j < n - 1 - i; j++) {
            if (arr[j] > arr[j + 1]) {
                swap(&arr[j], &arr[j + 1]);
                swapped = 1;
            }
        }

        if (!swapped)   /* no swaps this pass — array is sorted */
            break;
    }
}

void print_array(int arr[], int n) {
    for (int i = 0; i < n; i++)
        printf("%d ", arr[i]);
    printf("\n");
}

int main(void) {
    int n;
    printf("Enter number of elements: ");
    scanf("%d", &n);

    int arr[n];
    printf("Enter %d elements: ", n);
    for (int i = 0; i < n; i++)
        scanf("%d", &arr[i]);

    printf("Before sorting: ");
    print_array(arr, n);

    bubble_sort(arr, n);

    printf("After sorting:  ");
    print_array(arr, n);

    return 0;
}

Code Explanation

  • Outer loop (i) — runs n-1 passes. After pass i, the last i elements are already in their final positions, so the inner loop shrinks by one each time (j < n - 1 - i).
  • Inner loop (j) — scans adjacent pairs and swaps when out of order. Each iteration guarantees the current largest element reaches its correct position.
  • swapped flag — the key optimisation. If the inner loop completes without a single swap, the array is already sorted and the outer loop exits immediately. This gives O(n) best case on sorted input.

Sample Output

Enter number of elements: 6
Enter 6 elements: 64 34 25 12 22 11
Before sorting: 64 34 25 12 22 11
After sorting:  11 12 22 25 34 64

Time and Space Complexity

Case Time When it occurs
Best O(n) Array already sorted — one pass, no swaps, early exit
Average O(n²) Random input
Worst O(n²) Array sorted in reverse order
Space O(1) In-place — no extra array needed

Bubble Sort is stable — equal elements are never swapped, so their original order is preserved.

Bubble Sort vs Other Sorting Algorithms

Algorithm Best Average Worst Space Stable
Bubble Sort O(n) O(n²) O(n²) O(1) Yes
Insertion Sort O(n) O(n²) O(n²) O(1) Yes
Selection Sort O(n²) O(n²) O(n²) O(1) No
Quick Sort O(n log n) O(n log n) O(n²) O(log n) No
Merge Sort O(n log n) O(n log n) O(n log n) O(n) Yes

Among O(n²) algorithms, Insertion Sort is generally preferred over Bubble Sort in practice — it performs fewer writes and adapts better to partially sorted data. Use Bubble Sort when simplicity of explanation matters, not performance.

When to Use Bubble Sort

  • Teaching and learning — the simplest algorithm to visualise and explain
  • Very small arrays (n < 10) where O(n²) doesn't matter
  • Nearly-sorted data with the swapped optimisation — it exits in O(n)
  • Anywhere you need a stable, in-place sort and code simplicity matters more than speed

Related Sorting Programs in C


As an Amazon Associate we earn from qualifying purchases.

Further Reading

The definitive reference for C — The C Programming Language by Brian Kernighan and Dennis Ritchie. Covers every concept on this site: pointers, arrays, structs, file I/O, and the standard library. Worth having on your desk.

Binary search in C

C Program to implement Binary search. Binary search technique is simple searching technique which can be applied if the items to be compared are either in ascending order or descending order. The general idea used in binary search is similar to the way we search for the telephone number of a person in the telephone directory. Binary search is the divide and conquer strategy.Read more about C Programming Language.
[gist id=”7078221″]

Read more Similar C Programs
C Basic
Search Algorithms.

You can easily select the code by double clicking on the code area above.

To get regular updates on new C programs, you can Follow @c_program

You can discuss these programs on our Facebook Page. Start a discussion right now,

our page!

Share this program with your Facebook friends now! by liking it

(you can send this program to your friend using this button)

Like to get updates right inside your feed reader? Grab our feed!

(c) www.c-program-example.com

C Program to convert a given decimal number into its binary equivalent

C Program to convert a given decimal number into its binary equivalent. In this program we convert the given decimal based number system(0, 1, 2, 3, —–,9) to Binary number system(0 and 1). Read more about C Programming Language .

[gist id=”7072711″]

Read more Similar C Programs
Array In C

Number System

Simple C Programs

You can easily select the code by double clicking on the code area above.

To get regular updates on new C programs, you can Follow @c_program

You can discuss these programs on our Facebook Page. Start a discussion right now,

Share this program with your Facebook friends now! by liking it

Like to get updates right inside your feed reader? Grab our feed!

(c) www.c-program-example.com

C Program To Find The Largest Of 3 Numbers

C Program To Find The Biggest(Largest) Of 3 Numbers. In this program, We find the biggest of three number using simple else-if ladder. Read more about C Programming Language .
 [gist id=”7019035″ show_line_numbers="1" highlight="26-32"]

Read more Similar C Programs
Array In C
Number System

Simple C Programs

You can easily select the code by double clicking on the code area above.

To get regular updates on new C programs, you can Follow @c_program

You can discuss these programs on our Facebook Page. Start a discussion right now,  our page!

Share this program with your Facebook friends now! by liking it

Like to get updates right inside your feed reader? Grab our feed!
(c) www.c-program-example.com

C Program to find the array c such that c[i] = a[i ]+ b[n-1-i]

Example programs to solve the problems of Arrays in C,
a and b are two integers arrays each with n elements. C program to find the array c such that c[i]=a[i]+b[n-1-i]. Read more about C Programming Language .

[gist id=”7011382″]
Read more Similar C Programs
Array In C

Simple C Programs

You can easily select the code by double clicking on the code area above.

To get regular updates on new C programs, you can Follow @c_program

You can discuss these programs on our Facebook Page. Start a discussion right now,

 our page!

Share this program with your Facebook friends now! by liking it

 (you can send this program to your friend using this button)

Like to get updates right inside your feed reader? Grab our feed!

(c) www.c-program-example.com

C Program to classify the triangle as equilateral, isosceles and scalene

C Program to classify the triangle as equilateral, isosceles and scalene.
Equilateral triangle means all three side and angles are equal(i.e. 60 degree).
Isosceles triangle means any two side and angles are equal.
Scalene triangle means , any sides and any angles are not equal.
Read more about C Programming Language .

Read more Similar C Programs
Learn C Programming

Simple C Programs

To get regular updates on new C programs, you can Follow @c_program

You can discuss these programs on our Facebook Page. Start a discussion right now,

our page!

Share this program with your Facebook friends now! by liking it

(you can send this program to your friend using this button)

Like to get updates right inside your feed reader? Grab our feed!

(c) www.c-program-example.com

C Program to compute the area of an isosceles triangle

C Program to compute the area of an isosceles triangle. Isosceles Triangle is triangle, in which any two sides and angles are equal. Here, We check the given triangle is Isosceles or not also and print the suitable messages. Read more about C Programming Language .
Read more Similar C Programs
Learn C Programming

Simple C Programs

You can easily select the code by double clicking on the code area above.

To get regular updates on new C programs, you can Follow @c_program

You can discuss these programs on our Facebook Page. Start a discussion right now,

our page!

Share this program with your Facebook friends now! by liking it

(you can send this program to your friend using this button)

Like to get updates right inside your feed reader? Grab our feed!

–>

(c) www.c-program-example.com

Print “Hello World” Without Using Semicolon

How to Write a “Hello World” C program without using semicolon?
Asked in various interviews…
Read more about C Programming Language .

Read more Similar C Programs
C Interview Questions

Number Theory 
C Strings

You can easily select the code by double clicking on the code area above.
To get regular updates on new C programs, you can Follow @c_program
You can discuss these programs on our Facebook Page. Start a discussion right now,

our page!
Share this program with your Facebook friends now! by liking it

(you can send this program to your friend using this button)
Like to get updates right inside your feed reader? Grab our feed!

(c) www.c-program-example.com