Bubble Sort in C++
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 Algorithm
To sort a data set using bubble sort algorithm, follow the below steps:
- Start by comparing the first two elements. If they are in the wrong order, swap them.
- Continue this process for all elements moving from left to right. After the first pass, the largest element will be at the end.
- In the next pass, skip the last element since it's already sorted and repeat the above steps. The second-largest element will move to the second-last position.
- Repeat the steps until the entire array is sorted.
This algorithm is for increasing order but with minor changes, it can be implemented for any desired order.
C++ Program to Implement Bubble Sort
The below program sorts a vector using bubble sort:
// 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;
}
Output
1 2 4 5 8
Complexity Analysis of Bubble Sort
- Time Complexity: O(n2)
- Space Complexity: O (1)
Optimization
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++ 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;
}
Output
1 2 4 5 8
Time Complexity: O(n2)
Space Complexity: O(1)