Skip to main content

Selection Sort

//find the "minimum" element in unsorted array and "swap" it with element at the "begining".

#include <bits/stdc++.h>
using namespace std;

int main()
{

int n;
cin >> n;
int val;

vector<int> vec;
for (int i = 0; i < n; i++) {
cin >> val;
//v.at(i)=val; //best method
vec.emplace_back(val); //push_back can also be used
}

//selection sort
for (int i = 0; i < n - 1; i++) {
for (int j = i + 1; j < n; j++) {
//vec.at(i) and vec.at(j) is the best way
if (vec[j] < vec[i]) {
swap(vec.at(i), vec.at(j));
// int temp=vec[j];
// vec[j]=vec[i];
// vec[i]=temp;
}
}
}

for (auto element : vec)
cout << element << " ";

cout << endl;

//<==<==<==<==<==<==STL std::sort()⏩⏩⏩⏩⏩⏩
//also refer ⏩ http://www.cplusplus.com/reference/algorithm/sort/
//also refer ⏩ https://www.geeksforgeeks.org/sort-c-stl/
sort(vec.begin(), vec.begin() + n);
for (auto element2 : vec)
cout << element2 << " ";

return 0;
}