In: Computer Science
How to write a C++ of CountingSort function using 2D vector?
CountingSort(vector > array)
Input
# of rows: 2
Input Row 1: 9 8 7 6 3 2 1 5 4
Input Row 2: 1 2 4 3 5 6 9 8 7
Output
1,2,3,4,5,6,7,8,9
1,2,3,4,5,6,7,8,9
#include <algorithm>
#include <iostream>
#include <vector>
#include <bits/stdc++.h>
using namespace std;
vector<int> myVector;
void CountingSort(vector<int> vec,int m)
{ //sorting
sort(vec.begin(), vec.end());
auto end = vec.end();
for (auto it = vec.begin(); it != end; ++it) {
end = std::remove(it + 1, end, *it);
}
vec.erase(end, vec.end());
//display result
cout<<"output of input row "<<m+1<<"\n";
cout<<"\n\nAfter sorting vector : ";
for(auto i=vec.begin(); i<vec.end(); i++)
{
cout<<" "<<*i;
}
}
int main()
{
int n;
cout<<"enter number of rows:\n";
cin>>n;
//iterate number of rows times
for(int m=0;m<n;m++){
cout<<"\n Enter input elements for row "<<m+1<<":";
for (int i = 0; i < 9; i++)
{
int inp;
//prompt user to enter elements
cin >> inp; myVector.push_back(inp);
}
//function call
CountingSort(myVector,m);
}
return 0;
}