program of counting sort

Code:-

 in this program first we take three arrays one for input one for output and one for counting the frequency . we initialize the counting array to the zero . and while taking input from the user we will count the frequency of all the elements and store it in the array C . and we will also find the maximum among all the numbers (which we will use for loop condition further )  . after taking input we will have to find the cumulative frequency of the array C (i.e  c[i]=c[i]+c[i-1] ) . 

#include<stdio.h>
int main()
{
int a[50],b[50],n,k=0,c[10]={0};
printf(“Enter the element of the listn”);
scanf(“%d”,&n);
printf(“Enter the number of elements of the listn”);
for(int i=0;i<n;i++)
{
scanf(“%d”,&a[i]);
// frequency counting
c[a[i]]++;
// finding maximum number in the list
if(k<a[i])
k=a[i];
}
// cumulative frequency
for(int i=1;i<k+1;i++)
{
c[i]=c[i]+c[i1];
}
// logic
for(int i=n1;i>=0;i–)
{
int t=c[a[i]];
b[t]=a[i];
c[a[i]]–;
}
// the numbers after sorting are
printf(“Sorted list:-n”);
for(int i=1;i<=n;i++)
{
printf(“%d “,b[i]);
}
return 0;
}

Output:-

Enter the element of the list
7
Enter the number of elements of the list
1 2 1 0 3 2 1
Sorted list:-
0 1 1 1 2 2 3





Recommended Post:-

         MCQs:-

Leave a Reply

Your email address will not be published.