forked from silent-killer-11/Hacktoberfest-2022
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbubbleSort.cpp
More file actions
47 lines (40 loc) · 917 Bytes
/
Copy pathbubbleSort.cpp
File metadata and controls
47 lines (40 loc) · 917 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#include <iostream>
using namespace std;
// Function for bubble sort algorithm
void bubbleSort(vector<int> &arr ){
if (arr.size() == 1 || arr.size() == 0){
return;
}
bool swapped;
for (int i = 0; i < arr.size(); i++){
swapped = false;
for (int j = 0; j < arr.size()-i-1; j++){
// condition for swapping (if any element is greater than the next element, then swap them)
if (arr[j+1] < arr[j]){
swap(arr[j+1], arr[j]);
swapped = true;
}
}
}
if(swapped==false){
break;
}
}
int main()
{
int n;
cin >> n;
vector<int> arr;
for (int i = 0; i < n; i++){
int x;
cin >> x;
arr.push_back(x);
}
bubbleSort(arr);
// printing sorted array/vector
for (auto i : arr){
cout << i << " ";
}
cout << endl;
return 0;
}