forked from akkupy/codeDump
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcountingSort.cpp
More file actions
40 lines (32 loc) · 867 Bytes
/
Copy pathcountingSort.cpp
File metadata and controls
40 lines (32 loc) · 867 Bytes
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
#include <bits/stdc++.h>
using namespace std;
vector<int> countSort(vector<int>& inputArray)
{
int N = inputArray.size();
int M = 0;
for (int i = 0; i < N; i++) {
M = max(M, inputArray[i]);
}
vector<int> countArray(M + 1, 0);
for (int i = 0; i < N; i++) {
countArray[inputArray[i]]++;
}
for (int i = 1; i <= M; i++) {
countArray[i] += countArray[i - 1];
}
vector<int> outputArray(N);
for (int i = N - 1; i >= 0; i--) {
outputArray[countArray[inputArray[i]] - 1] = inputArray[i];
countArray[inputArray[i]]--;
}
return outputArray;
}
int main()
{
vector<int> inputArray = { 4, 3, 12, 1, 5, 5, 3, 9 };
vector<int> outputArray = countSort(inputArray);
for (int i = 0; i < inputArray.size(); i++) {
cout << outputArray[i] << " ";
}
return 0;
}