-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsort_Counting.cpp
More file actions
38 lines (29 loc) · 845 Bytes
/
sort_Counting.cpp
File metadata and controls
38 lines (29 loc) · 845 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
#include <bits/stdc++.h>
using namespace std;
void countSort(vector<int>&array, int size)
{
int max = array[0];
for (int i = 1; i < size; i++)
{
if (array[i] > max) max = array[i];
}
vector<int>output(size,0);
vector<int>count(max+10,0);
for (int i = 0; i < size; i++) count[array[i]]++;
for (int i = 1; i <= max; i++) count[i] += count[i - 1];
// Find the index of each element of the original array in count array, and
// place the elements in output array
for (int i = size - 1; i >= 0; i--) {
output[--count[array[i]] ] = array[i];
// count[array[i]]--;
}
for (int i = 0; i < size; i++) array[i] = output[i];
}
int main() {
int n;
cin>>n;
vector<int>array(n);
for(int i=0;i<n;i++) cin>>array[i];
countSort(array, n);
for (int i = 0; i < n; i++) cout << array[i] << " ";
}