Skip to content

Commit 87a2775

Browse files
authored
Merge pull request ephremdeme#119 from Kanhakhatri065/master
counting sort implemented in C++
2 parents 1e5a04f + 92cb33f commit 87a2775

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
#include <bits/stdc++.h>
2+
3+
using namespace std;
4+
5+
void countingsort(vector<int> &v, int n) {
6+
int largest_element_of_vector = *max_element(v.begin(), v.end());
7+
8+
vector<int> hash(largest_element_of_vector + 1, 0);
9+
10+
for(int i = 0;i < n;i++) {
11+
hash[v[i]]++;
12+
}
13+
14+
int idx = 0;
15+
for(int i = 0;i <= largest_element_of_vector;i++) {
16+
while(hash[i] > 0) {
17+
v[idx] = i;
18+
hash[i]--;
19+
idx++;
20+
}
21+
}
22+
}
23+
24+
int main() {
25+
int n;
26+
cin >> n;
27+
28+
vector<int> v(n);
29+
for(int i = 0;i < n;i++) {
30+
cin >> v[i];
31+
}
32+
33+
countingsort(v, n);
34+
35+
for(int i = 0;i < n;i++) {
36+
cout << v[i] << " ";
37+
}
38+
cout << endl;
39+
40+
return 0;
41+
}

0 commit comments

Comments
 (0)