C++ Program for Bubble Sort with Example and Explanation
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
How to Think About It
Algorithm
Code
#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; }
Dry Run
Let's trace the array {5, 3, 8, 4, 2} through the bubble sort code.
Initial array
arr = {5, 3, 8, 4, 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}
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}
Third pass swaps
Compare 3 and 4, no swap Compare 4 and 2, swap -> {3, 2, 4, 5, 8}
Fourth pass swaps
Compare 3 and 2, swap -> {2, 3, 4, 5, 8}
| Pass | Array State |
|---|---|
| 1 | 3 5 4 2 8 |
| 2 | 3 4 2 5 8 |
| 3 | 3 2 4 5 8 |
| 4 | 2 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
#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; }
#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; }
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.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Basic Bubble Sort | O(n^2) | O(1) | Learning sorting basics |
| Optimized Bubble Sort | O(n) best, O(n^2) worst | O(1) | Nearly sorted data |
| std::sort (QuickSort) | O(n log n) | O(log n) | General purpose sorting |