Skip to content

Commit

Permalink
Merge pull request #119 from Kanhakhatri065/master
Browse files Browse the repository at this point in the history
counting sort implemented in C++
  • Loading branch information
ephremdeme authored Oct 1, 2020
2 parents 1e5a04f + 92cb33f commit 87a2775
Showing 1 changed file with 41 additions and 0 deletions.
41 changes: 41 additions & 0 deletions sorting-algorithms/countingsort.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
#include <bits/stdc++.h>

using namespace std;

void countingsort(vector<int> &v, int n) {
int largest_element_of_vector = *max_element(v.begin(), v.end());

vector<int> hash(largest_element_of_vector + 1, 0);

for(int i = 0;i < n;i++) {
hash[v[i]]++;
}

int idx = 0;
for(int i = 0;i <= largest_element_of_vector;i++) {
while(hash[i] > 0) {
v[idx] = i;
hash[i]--;
idx++;
}
}
}

int main() {
int n;
cin >> n;

vector<int> v(n);
for(int i = 0;i < n;i++) {
cin >> v[i];
}

countingsort(v, n);

for(int i = 0;i < n;i++) {
cout << v[i] << " ";
}
cout << endl;

return 0;
}

0 comments on commit 87a2775

Please sign in to comment.