Last active
July 7, 2017 10:32
-
-
Save ravisumit33/a5cf3225e7a200024b7ad5e179538c67 to your computer and use it in GitHub Desktop.
Counting_Sort.cpp created by ravisumit33 - https://repl.it/JRi0/2
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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