-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCount_sort.cpp
More file actions
46 lines (42 loc) · 866 Bytes
/
Count_sort.cpp
File metadata and controls
46 lines (42 loc) · 866 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
#include <bits/stdc++.h>
using namespace std;
int maxim(int *a, int n){
int max = a[0];
for(int i=1;i<n;i++){
if(a[i] > max) max = a[i];
}
return max;
}
void countSort(int *a, int n){
int max = maxim(a, n);
int count[max+1] ={0};
for(int i=0;i<n;i++){
count[a[i]]++;
}
for(int i = 1;i<n;i++){
count[i] = count[i-1] + count[i];
}
int tmp[n];
for(int i = 0;i<n;i++){
tmp[--count[a[i]]] = a[i];
}
for(int i = 0;i<n;i++){
a[i] = tmp[i];
}
}
int main(){
int n;
cout<<"Enter size of array:"<<endl;
cin>>n;
int a[n];
cout<<"Enter elements of array:"<<endl;
for(int i = 0; i < n; i++){
cin>>a[i];
}
countSort(a, n);
cout<<"Sorted array is:"<<endl;
for(int i = 0; i < n; i++){
cout<<a[i]<<" ";
}
return 0;
}