I have to write a C++ function called sort that will take in a reference to a ve
ID: 3719256 • Letter: I
Question
I have to write a C++ function called sort that will take in a reference to a vector and sort it in ascending order. This is my function so far, I just don't know how to sort it in ascending order.
#include <iostream>
#include <vector>
using namespace std;
vector<int> sort(vector<int> &a)
{
int max;
vector<int> sorted;
for(int i=0; i<a.size; i++)
{
}
return sorted;
}
int main() {
int n;
cin >> n;
vector<int> a;
int temp;
while(true)
{
cin >> temp;
if(temp <0)
{
break;
}
else
{
a.push_back(temp);
}
}
sort(a);
return 0;
}
Explanation / Answer
#include <iostream>
#include <vector>
using namespace std;
vector<int> sort(vector<int> &a)
{
int m, temp;
for (int i = 0; i < a.size()-1; i++)
{
m = i;
for (int j = i + 1; j < a.size(); j++)
{
if (a[j] < a[m])
{
m = j;
}
}
temp = a[m];
a[m] = a[i];
a[i] = temp;
}
return a;
}
int main() {
int n;
cin >> n;
vector<int> a;
int temp;
while(true)
{
cin >> temp;
if(temp <0)
{
break;
}
else
{
a.push_back(temp);
}
}
a = sort(a);
for (int i = 0; i < a.size(); i++)
cout << a[i] << " ";
return 0;
}
**Comment for any further queries.