0
0
CppProgramBeginner · 2 min read

C++ Program for Bubble Sort with Example and Explanation

A C++ program for bubble sort repeatedly compares adjacent elements and swaps them if they are in the wrong order using nested loops, like for (int i = 0; i < n-1; i++) for (int j = 0; j < n-i-1; j++) if (arr[j] > arr[j+1]) swap(arr[j], arr[j+1]);.
📋

Examples

Input5 3 8 4 2
Output2 3 4 5 8
Input1 2 3 4 5
Output1 2 3 4 5
Input9 7 5 3 1
Output1 3 5 7 9
🧠

How to Think About It

To sort numbers using bubble sort, think of repeatedly passing through the list and swapping neighbors if they are out of order. Each pass pushes the largest unsorted number to the end, so you reduce the range each time until everything is sorted.
📐

Algorithm

1
Get the list of numbers to sort.
2
Repeat for each element except the last:
3
Compare each pair of neighbors in the unsorted part.
4
Swap them if the left one is bigger than the right one.
5
After all passes, the list will be sorted.
💻

Code

cpp
#include <iostream>
using namespace std;

int main() {
    int arr[] = {5, 3, 8, 4, 2};
    int n = sizeof(arr) / sizeof(arr[0]);

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

    for (int i = 0; i < n; i++) {
        cout << arr[i] << " ";
    }
    cout << endl;
    return 0;
}
Output
2 3 4 5 8
🔍

Dry Run

Let's trace the array {5, 3, 8, 4, 2} through the bubble sort code.

1

Initial array

arr = {5, 3, 8, 4, 2}

2

First pass swaps

Compare 5 and 3, swap -> {3, 5, 8, 4, 2} Compare 5 and 8, no swap Compare 8 and 4, swap -> {3, 5, 4, 8, 2} Compare 8 and 2, swap -> {3, 5, 4, 2, 8}

3

Second pass swaps

Compare 3 and 5, no swap Compare 5 and 4, swap -> {3, 4, 5, 2, 8} Compare 5 and 2, swap -> {3, 4, 2, 5, 8}

4

Third pass swaps

Compare 3 and 4, no swap Compare 4 and 2, swap -> {3, 2, 4, 5, 8}

5

Fourth pass swaps

Compare 3 and 2, swap -> {2, 3, 4, 5, 8}

PassArray State
13 5 4 2 8
23 4 2 5 8
33 2 4 5 8
42 3 4 5 8
💡

Why This Works

Step 1: Compare adjacent elements

The code uses if (arr[j] > arr[j + 1]) to check if neighbors are out of order.

Step 2: Swap if needed

If the left element is bigger, swap(arr[j], arr[j + 1]) exchanges their positions.

Step 3: Repeat passes

Multiple passes push the largest unsorted element to the end, shrinking the unsorted range.

🔄

Alternative Approaches

Optimized Bubble Sort with Early Stop
cpp
#include <iostream>
using namespace std;

int main() {
    int arr[] = {5, 3, 8, 4, 2};
    int n = sizeof(arr) / sizeof(arr[0]);
    bool swapped;

    for (int i = 0; i < n - 1; i++) {
        swapped = false;
        for (int j = 0; j < n - i - 1; j++) {
            if (arr[j] > arr[j + 1]) {
                swap(arr[j], arr[j + 1]);
                swapped = true;
            }
        }
        if (!swapped) break; // stop if no swaps
    }

    for (int i = 0; i < n; i++) cout << arr[i] << " ";
    cout << endl;
    return 0;
}
Stops early if the array is already sorted, improving best-case performance.
Using std::sort from <algorithm>
cpp
#include <iostream>
#include <algorithm>
using namespace std;

int main() {
    int arr[] = {5, 3, 8, 4, 2};
    int n = sizeof(arr) / sizeof(arr[0]);
    sort(arr, arr + n);
    for (int i = 0; i < n; i++) cout << arr[i] << " ";
    cout << endl;
    return 0;
}
Uses built-in efficient sort, simpler and faster but no manual bubble sort logic.

Complexity: O(n^2) time, O(1) space

Time Complexity

Bubble sort uses two nested loops each up to n, so worst and average time is O(n^2). Best case is O(n) if optimized with early stop.

Space Complexity

It sorts the array in place using only a few extra variables, so space complexity is O(1).

Which Approach is Fastest?

Using std::sort is fastest for large data. Optimized bubble sort is better than basic but still slower than efficient algorithms.

ApproachTimeSpaceBest For
Basic Bubble SortO(n^2)O(1)Learning sorting basics
Optimized Bubble SortO(n) best, O(n^2) worstO(1)Nearly sorted data
std::sort (QuickSort)O(n log n)O(log n)General purpose sorting
💡
Use a flag to stop early if no swaps happen in a pass to save time on sorted arrays.
⚠️
Forgetting to reduce the inner loop range each pass causes unnecessary comparisons.