forked from Vishal1003/Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCountingSort.cpp
More file actions
59 lines (47 loc) · 1.25 KB
/
CountingSort.cpp
File metadata and controls
59 lines (47 loc) · 1.25 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
void Print(vector<int> &arr){
for(int i=0;i<arr.size();i++){
cout<<arr[i]<<" ";
}
cout<<endl;
}
void CountingSort(vector<int> &A, vector<int> &Aux, vector<int> &sorted) {
int N=A.size();
// First, find the maximum value in A[]
int K = 0;
for(int i=0; i<N; i++) {
K = max(K, A[i]);
}
// Initialize the elements of Aux[] with 0
for(int i=0 ; i<=K; i++) {
Aux[i] = 0;
}
// Store the frequencies of each distinct element of A[],
// by mapping its value as the index of Aux[] array
for(int i=0; i<N; i++) {
Aux[A[i]]++;
}
int j = 0;
for(int i=0; i<=K; i++) {
int tmp = Aux[i];
// Aux stores which element occurs how many times,
// Add i in sortedA[] according to the number of times i occured in A[]
while(tmp--) {
//cout << Aux[i] << endl;
sorted[j] = i;
j++;
}
}
}
int main()
{
vector<int> A{5,2,9,5,2,3,5};
vector<int> Aux{0,0,2,1,0,3,0,0,0,2}; //Aux stores count of element 'i' in 'A'
vector<int> sorted(A.size());
CountingSort(A,Aux,sorted);
Print(sorted);
return 0;
}