Skip to main content

Bubble Sort

//Bubble Sort⏩ Repetedly swap two "adjacent" elements if they are in wrong order.

#include <iostream>
#include <vector>
#include <algorithm>
// #include <numeric>

using namespace std;

int main()
{

freopen("inputf.in", "r", stdin);
freopen("outputf.in", "w", stdout);

int n;
cin >> n;

vector<int> v(n);

//Assigning values to the vector
for (int i = 0; i < v.size(); i++) {
cin >> v.at(i);
}


//Bubble Sort Algorithm
int count = 1;
while (count < n) {
for (int i = 0; i < n - count; i++) {
if (v.at(i) > v.at(i + 1)) {
swap(v.at(i), v.at(i + 1)); //#include <algorithm>
//OR swap(v[i], v[i+1]);
//OR int temp = v.at(i);
// v.at(i)=v.at(j);
// v.at(j)=temp;
}
}
count++;
}


//another way of Bubble Sort
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (v.at(j) > v.at(j + 1)) {
swap(v.at(j), v.at(j+1));
}
}
}

//printing the Vector
for (auto el : v)
cout << el << " ";


//<==<==<==<==<==<==STL std::sort()⏩⏩⏩⏩⏩⏩
//also refer ⏩ http://www.cplusplus.com/reference/algorithm/sort/
//also refer ⏩ https://www.geeksforgeeks.org/sort-c-stl/

// sort(v.begin(), v.begin() + v.size());

// for (auto el : v)
// cout << el << " ";

return 0;

}