Bubble Sort in C++
Bubble Sort Algorithm in C++ (Complete Implementation).
1#include <iostream>2using namespace std;34void bubbleSort(int arr[], int n) {5 for (int i = 0; i < n - 1; i++) {6 bool swapped = false;7 for (int j = 0; j < n - i - 1; j++) {8 if (arr[j] > arr[j + 1]) {9 // Swap elements10 swap(arr[j], arr[j + 1]);11 swapped = true;12 }13 }14 // If no swapping occurred, array is sorted15 if (!swapped) break;16 }17}1819void printArray(int arr[], int n) {20 for (int i = 0; i < n; i++) {21 cout << arr[i] << " ";22 }23 cout << endl;24}2526int main() {27 int arr[] = {64, 34, 25, 12, 22, 11, 90};28 int n = sizeof(arr) / sizeof(arr[0]);2930 cout << "Original array: ";31 printArray(arr, n);3233 bubbleSort(arr, n);3435 cout << "Sorted array: ";36 printArray(arr, n);3738 return 0;39}
Output
Original array: 64 34 25 12 22 11 90 Sorted array: 11 12 22 25 34 64 90
What's going on
The program sorts an array of integers using the Bubble Sort algorithm. For example:
Bubble Sort works by repeatedly comparing adjacent elements and swapping them if they're in the wrong order, "bubbling" the largest elements to the end in each pass.
Header File Used
This header provides:
1#include <iostream>
Understanding Bubble Sort
Algorithm Concept
:
Visual Example
:
Initial: [64, 34, 25, 12, 22, 11, 90]
Pass 1: Compare and swap adjacent pairs
Pass 2: Repeat for remaining elements
Function: bubbleSort()
void bubbleSort(int arr[], int n) {
for (int i = 0; i < n - 1; i++) {
bool 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;
}
}
How it works
:
Step-by-Step Algorithm
Pass 1
(i = 0):
Pass 2
(i = 1):
Optimization
:
Understanding the Loops
Outer Loop: for (int i = 0; i < n - 1; i++)
Inner Loop: for (int j = 0; j < n - i - 1; j++)
Why n - i - 1?
:
Swap Operation
if (arr[j] > arr[j + 1]) {
swap(arr[j], arr[j + 1]);
swapped = true;
}
How it works
:
Example
:
Optimization: Early Termination
bool swapped = false;
if (!swapped) break;
1// ... inner loop ...
How it works
:
Example
:
Time and Space Complexity
Time Complexity
:
Space Complexity
: O(1)
Stability
: Stable
When to Use Bubble Sort
Educational Purposes
:
Small Datasets
:
Nearly Sorted Data
:
Not Recommended For
:
Important Considerations
Array Bounds
:
Optimization
:
In-Place Sorting
:
return 0;
This ends the program successfully.
Each pass parks the next-largest value at the end. The swapped flag skips extra passes on data that's already sorted. It's still O(n²) — fine for learning, not for a million items.