Skip to content

Instantly share code, notes, and snippets.

@ravisumit33
Last active July 7, 2017 10:32
Show Gist options
  • Save ravisumit33/a5cf3225e7a200024b7ad5e179538c67 to your computer and use it in GitHub Desktop.
Save ravisumit33/a5cf3225e7a200024b7ad5e179538c67 to your computer and use it in GitHub Desktop.
Counting_Sort.cpp created by ravisumit33 - https://repl.it/JRi0/2
#include <iostream>
#include <vector>
#include <algorithm> // std::max_element
using namespace std;
void counting_sort(vector<int> &v){
int mx = *max_element(v.begin(), v.end());
vector<int> count(mx+1, 0);
int sz = v.size();
vector<int> ans(sz);
for(int i=0; i<sz; i++) count[v[i]]++;
for(int i=1; i<sz; i++) count[i] += count[i-1];
for(int i=mx; i>-1; i--) ans[--count[v[i]]] = v[i];
v.assign(ans.begin(), ans.end());
}
int main(){
int n; cin >> n;
vector<int> v(n);
for(int i=0; i<n; i++) cin >> v[i];
counting_sort(v);
for(int i=0; i<n; i++) cout << v[i] << ' ';
cout << '\n';
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment