Skip to content
This repository was archived by the owner on Nov 26, 2019. It is now read-only.

Counting Sort #180

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions algorithms/Sorting/Counting_sort/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
## Implementation of Counting sort algorithm
### Complexity if max(O(n), O(max_value))
'''
Input:
5
9 4 6 21 3
'''
'''
Output:
3 4 6 9 21
'''
31 changes: 31 additions & 0 deletions algorithms/Sorting/Counting_sort/counting_sort.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
#include<iostream>
#include<bits/stdc++.h>
using namespace std;

// Complexeity is O(n + max_val) in case of integer sorting
void csort(int* a, int n){
unordered_map<int, int> hash;
int max_val = INT_MIN;
for(int i=0; i<n; i++){
hash[a[i]]++;
if(a[i]>max_val)max_val = a[i];
}
int j=0;
for(int i=0; i<=max_val; i++){
while(hash[i]--){
a[j]=i;
j++;
}
}
}
int main(){
int n;
int* a;
cin>>n;
a = new int[n];
for(int i=0; i<n; i++)
cin>>a[i];
csort(a, n);
for(int i=0; i<n; i++)cout<<a[i]<<' ';
return 0;
}