Skip to content

Commit 11776ff

Browse files
authored
Bubble Sorting algorithm
1 parent f8318bc commit 11776ff

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

BubbleSorted.cpp

+39
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
#include <iostream>
2+
#include <algorithm>
3+
#include <vector>
4+
using namespace std;
5+
class BubbleSort
6+
{
7+
public:
8+
void sort(vector<int>& arr) // time complexity is O(n^2)
9+
{
10+
bool check = false;
11+
for (size_t i = 0; i < arr.size() - 1; i++)
12+
{
13+
for (size_t j = 0; j < arr.size() - i-1; j++)
14+
{
15+
if (arr.at(j) > arr.at(j + 1))
16+
{
17+
swap(arr[j], arr[j + 1]);
18+
check = true;
19+
}
20+
}
21+
if (!check) // making this algoriithm adaptive by checking the conditon in 1st pass. In adaptive case, time complexity will be O(n)
22+
break;
23+
}
24+
}
25+
};
26+
int main()
27+
{
28+
vector<int> arr{2, 36, 1, 0, 2};
29+
BubbleSort sorting;
30+
sorting.sort(arr);
31+
cout << "[";
32+
for (auto i : arr)
33+
{
34+
cout << i << " ";
35+
}
36+
cout << "]" << endl;
37+
38+
return 0;
39+
}

0 commit comments

Comments
 (0)