Last Updated : 23 Jul, 2025
Bubble Sort Algorithm is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. It is often used to introduce the concept of a sorting and is particularly suitable for sorting small datasets.
In this article, we will learn how to implement bubble sort in C++.
Bubble Sort AlgorithmTo sort a data set using bubble sort algorithm, follow the below steps:
This algorithm is for increasing order but with minor changes, it can be implemented for any desired order.
C++ Program to Implement Bubble SortThe below program sorts a vector using bubble sort:
C++
// C++ program for the implementation of Bubble sort
#include <bits/stdc++.h>
using namespace std;
void bubbleSort(vector<int>& v) {
int n = v.size();
// Outer loop that corresponds to the number of
// elements to be sorted
for (int i = 0; i < n - 1; i++) {
// Last i elements are already
// in place
for (int j = 0; j < n - i - 1; j++) {
// Comparing adjacent elements
if (v[j] > v[j + 1])
// Swapping if in the wrong order
swap(v[j], v[j + 1]);
}
}
}
int main() {
vector<int> v = {5, 1, 4, 2, 8};
// Sorting the vector v
bubbleSort(v);
for (auto i : v)
cout << i << " ";
return 0;
}
Complexity Analysis of Bubble Sort
We may notice in the above algorithm that if the inner loop does not cause any swap, the array is already sorted, but it will still run O(n2) time. This can be optimized by stopping the algorithm if the inner loop didn’t cause any swap. We can use a flag variable to indicate whether the swap happened or not.
C++
// C++ program for optimized implementation of Bubble sort
#include <bits/stdc++.h>
using namespace std;
// An optimized version of Bubble Sort
void bubbleSort(vector<int>& v) {
int n = v.size();
for (int i = 0; i < n - 1; i++) {
// Creating a flag to denote the case wwhen array
// is sorted and doesnt cause any swap
bool flag = false;
for (int j = 0; j < n - i - 1; j++) {
if (v[j] > v[j + 1]) {
swap(v[j], v[j + 1]);
// Setting flag true when swap happened
flag = true;
}
}
// Checking if the flag is set or not
if (!flag)
break;
}
}
int main() {
vector<int> v = {5, 1, 4, 2, 8};
bubbleSort(v);
for (auto i : v)
cout << i << " ";
return 0;
}
Time Complexity: O(n2)
Space Complexity: O(1)
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4