counting sort(stable)

#include<stdio.h>
#include<malloc.h>

void counting_sort(int a[], int sorted[],int k,int size)
{
int *c=(int *)malloc((k+1)*sizeof(int));
int i=0;
for(;i<k+1;i++)
c[i]=0;
for(i=0;i<size;i++)
c[a[i]]=c[a[i]]+1;
//now,c[i] contains the numbers of elements equals to i
for(i=1;i<k+1;i++)
c[i]=c[i]+c[i-1];
//now ,c[i] contains the numbers of elements equals or less than i
for(i=size-1;i>-1;i--)
{
sorted[c[a[i]]-1]=a[i];
c[a[i]]=c[a[i]]-1;
}
free(c);
}

int main()
{
int a[10]={9,5,2,6,7,1,0,3,8,4};
int b[10]={-1};
counting_sort(a,b,9,10);
int i=0;
for(;i<10;i++)
printf("%d ",b[i]);
printf("\n");
return 0;
}

你可能感兴趣的:(C++,c,C#)