Apply Counting Sort on Data and Arrange it.
Program:
#include<stdio.h>
#include<malloc.h>
voidcounting_sort(int *,int *,int);
int * create_random_data(int );
int main()
{
int *a,*b;
intn,i;
printf("Enter number\n");
scanf("%d",&n);
a=create_random_data(n);
if(a==NULL)
{
printf("Not enough
memory");
return;
}
b=(int *)malloc(n*(sizeof(int)));
counting_sort(a,b,n);
printf("\n");
printf("The Sorted array of
counting sort is:\n ");
for (i = 0; i < n; i++)
{
printf("%d\n
", b[i]);
}
}
int * create_random_data(int n)
{
int *p;
int i;
p=(int
*)malloc(n*(sizeof(int)));
if(p==NULL)
{
return NULL;
}
for(i=0;i<n;i++)
{
p[i]=rand()%n;
printf("%d\t",p[i]);
}
return p;
}
voidcounting_sort(int *a,int *b,int n)
{
int *c;
inti,max=a[0];
for(i=1;i<n;i++)
{
if(a[i]>max)
{
max=a[i];
}
}
c=(int *)malloc((max+1)*sizeof(int));
for(i=0;i<max;i++)
c[i]=0;
for(i=0;i<n;i++)
{
c[a[i]]=c[a[i]]+1;
}
for(i=1;i<=max;i++)
{
c[i]=c[i]+c[i-1];
}
for(i=0;i<n;i++)
{
b[c[a[i]]-1]=a[i];
c[a[i]]=c[a[i]]-1;
}
}
No comments:
Post a Comment