Just write your sorting code in ad hoc functions. You should avoid
C
like arrays for such a task.
Try
#include <iostream>
#include <vector>
#include <utility>
using namespace std;
void sort_ascending(vector<int> & v);
void sort_descending(vector <int> & v);
int main()
{
size_t n;
cout << "enter n for the numbers you want to sort" << endl;
cin >> n;
cout << endl;
vector<int> v(n);
for (size_t i =0; i < n; ++i)
{
cout << "enter number " << (i+1) << " of " << n << endl;
cin >> v[i];
}
cout << "ascending:\n";
sort_ascending( v);
for (auto x : v)
cout << x << "\n";
cout << "descending:\n";
sort_descending(v);
for (auto x : v)
cout << x << "\n";
}
void sort_ascending( vector<int> & v)
{
for (size_t i=0; i < v.size()-1; ++i)
for (size_t j= i+1; j < v.size(); ++j)
if ( v[i] > v[j] ) swap(v[i], v[j]);
}
void sort_descending( vector<int> & v)
{
for (size_t i=0; i < v.size()-1; ++i)
for (size_t j= i+1; j < v.size(); ++j)
if ( v[i] < v[j] ) swap(v[i], v[j]);
}
That's a possible implementation of an
exercise. On the other hand, if you are writing production code, then discard your own (bubble!) implementation of
sort
and use the one provided by the
C++
standard library instead.
#include <iostream>
#include <algorithm>
#include <functional>
#include <vector>
using namespace std;
int main()
{
size_t n;
cout << "enter n for the numbers you want to sort" << endl;
cin >> n;
cout << endl;
vector<int> v(n);
for (size_t i =0; i < n; ++i)
{
cout << "enter number " << (i+1) << " of " << n << endl;
cin >> v[i];
}
cout << "ascending:\n";
sort(v.begin(), v.end());
for (auto x : v)
cout << x << "\n";
cout << "descending:\n";
sort(v.begin(), v.end(), std::greater<int>());
for (auto x : v)
cout << x << "\n"
}