-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcountsort.cpp
More file actions
54 lines (51 loc) · 1.2 KB
/
countsort.cpp
File metadata and controls
54 lines (51 loc) · 1.2 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
#include <iostream>
#include <vector>
using namespace std;
class Solution
{
public:
void countSort(vector<int> &arr)
{
// find max
int max = -1;
int n = arr.size();
for (int i = 0; i < n + 1; i++)
{
if (arr[i] > max)
max = arr[i];
}
// create frequency array of size max +1
vector<int> freq(max + 1);
for (int i = 0; i < max; i++)
{
freq[arr[i]]++;
}
// convert frequency array to cummulative array
for (int i = 1; i < max + 1; i++)
{
freq[i] = freq[i] + freq[i - 1];
}
// create a temporary array of size n . for making it stable sort we will traverse given array from backside
vector<int> ans(n);
for (int i = n - 1; i >= 0; i--)
{
ans[--freq[arr[i]]] = arr[i];
}
// copy to the original
for (int i = 0; i < n; i++)
{
arr[i] = ans[i];
}
}
};
int main()
{
vector<int> arr = {6, 8, 5, 2, 7, 4, 8, 7};
Solution sol;
sol.countSort(arr);
for (int i = 0; i < arr.size(); i++)
{
cout << arr[i] << " ";
}
cout << endl;
}