Skip to content

Commit 74411f7

Browse files
authored
HACKTOBERFEST-ACCEPTED
1 parent 3859635 commit 74411f7

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

C++/countsort1.cpp

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
#include<iostream>
2+
#include<cmath>
3+
using namespace std;
4+
5+
void countsort(int arr[],int n)
6+
{
7+
int k=arr[0];
8+
for(int i=0;i<n;i++) {
9+
k=max(k,arr[i]);
10+
}
11+
int count[10]={0};
12+
for(int i=0;i<n;i++) {
13+
count[arr[i]]++;
14+
}
15+
for(int i=1;i<=k;i++) {
16+
count[i]+=count[i-1];
17+
}
18+
int output[n];
19+
for(int i=n-1;i>=0;i--) {
20+
output[--count[arr[i]]]=arr[i];
21+
}
22+
for(int i=0;i<n;i++) {
23+
arr[i]=output[i];
24+
}
25+
}
26+
27+
int main()
28+
{
29+
int n;
30+
cout<<"Enter the number of elements. \n";
31+
cin>>n;
32+
int arr[n];
33+
cout<<"Enter the elements. \n";
34+
for(int i=0;i<n;i++) {
35+
cin>>arr[i];
36+
}
37+
countsort(arr,n);
38+
cout<<"Ans: \n";
39+
for(int i=0;i<n;i++) {
40+
cout<<arr[i]<<" ";
41+
}
42+
return 0;
43+
}

0 commit comments

Comments
 (0)