forked from shivprime94/Data-Structure-Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCountingSort.cpp
More file actions
49 lines (40 loc) · 926 Bytes
/
CountingSort.cpp
File metadata and controls
49 lines (40 loc) · 926 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
41
42
43
44
45
46
47
48
49
//Counting Sort
#include <bits/stdc++.h>
using namespace std;
void CountSort(vector<int> &arr)
{
int max = *max_element(arr.begin(), arr.end());
int min = *min_element(arr.begin(), arr.end());
int range = max - min + 1;
vector<int> count(range), output(arr.size());
for (int i = 0; i < arr.size(); i++)
count[arr[i] - min]++;
for (int i = 1; i < count.size(); i++)
count[i] += count[i - 1];
for (int i = arr.size() - 1; i >= 0; i--)
{
output[count[arr[i] - min] - 1] = arr[i];
count[arr[i] - min]--;
}
for (int i = 0; i < arr.size(); i++)
arr[i] = output[i];
}
int main()
{
//the length of array
int n;
cin >> n;
vector<int> v;
for (int i = 0; i < n; i++)
{
int x;
cin >> x;
v.push_back(x);
}
CountSort(v);
for (auto x : v)
{
cout << x << " ";
}
return 0;
}