Bubble Sort is one of the simplest and most well-known comparison-based sorting algorithms. It repeatedly steps through the list, compares adjacent elements, and swaps them if they are in the wrong order. This process is repeated until the array is fully sorted.
Although it is not efficient for large datasets due to its quadratic time complexity, Bubble Sort is excellent for teaching the core principles of sorting algorithms — such as iteration, comparison, and swapping.
Case | Time Complexity |
---|---|
Best | O(n) |
Average | O(n²) |
Worst | O(n²) |
#include <iostream>
using namespace std;
void bubbleSort(int arr[], int n) {
bool swapped;
for (int i = 0; i < n - 1; i++) {
swapped = false;
// Compare adjacent elements
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
// Swap them
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
swapped = true;
}
}
// Print array after each pass
cout << "After pass " << i + 1 << ": ";
for (int k = 0; k < n; k++) {
cout << arr[k] << " ";
}
cout << endl;
// If no swaps were made, the array is already sorted
if (!swapped) break;
}
}
void printArray(int arr[], int n) {
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
cout << endl;
}
int main() {
int arr[] = {64, 34, 25, 12, 22, 11, 90};
int n = sizeof(arr) / sizeof(arr[0]);
cout << "Original array:\n";
printArray(arr, n);
bubbleSort(arr, n);
cout << "\nSorted array:\n";
printArray(arr, n);
return 0;
}
Original array:
64 34 25 12 22 11 90
After pass 1: 34 25 12 22 11 64 90
After pass 2: 25 12 22 11 34 64 90
After pass 3: 12 22 11 25 34 64 90
After pass 4: 12 11 22 25 34 64 90
After pass 5: 11 12 22 25 34 64 90
After pass 6: 11 12 22 25 34 64 90
Sorted array:
11 12 22 25 34 64 90
Let’s sort:
[64, 34, 25, 12, 22, 11, 90]
➡ Largest element (90) has bubbled to the end.
Now ignore the last element (already sorted):
[34, 25, 12, 22, 11, 64, 90]
→ Result after swaps: [25, 12, 22, 11, 34, 64, 90]
[25, 12, 22, 11, 34, 64, 90]
→ Result: [12, 22, 11, 25, 34, 64, 90]
[12, 22, 11, 25, 34, 64, 90]
→ Result: [12, 11, 22, 25, 34, 64, 90]
[12, 11, 22, 25, 34, 64, 90]
→ Result: [11, 12, 22, 25, 34, 64, 90]
Already sorted → no swaps → exit early.
[11, 12, 22, 25, 34, 64, 90]