-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCountSort.cpp
More file actions
49 lines (46 loc) · 1.01 KB
/
CountSort.cpp
File metadata and controls
49 lines (46 loc) · 1.01 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
#include <iostream>
#include <vector>
using namespace std;
class CountSort
{
public:
void sort(vector<int> &arr) //time complexity is O(m+n)
{
int max = arr.at(0);
for (size_t i = 0; i < arr.size(); i++)
{
if (arr.at(i) > max)
max = arr.at(i);
}
vector<int> another(max + 1);
for (size_t i = 0; i < arr.size(); i++)
{
another.at(arr.at(i)) = another.at(arr.at(i)) + 1;
}
size_t j{0};
int value;
for (size_t i = 0; i < another.size(); i++)
{
value = another.at(i);
while (value)
{
arr.at(j) = i;
j++;
value--;
}
}
}
};
int main()
{
vector<int> arr{4, 2, 7, 0};
CountSort sorting;
sorting.sort(arr);
cout << "[";
for (auto i : arr)
{
cout << i << " ";
}
cout << "]" << endl;
return 0;
}