首页 > 代码库 > 计数排序

计数排序

#include<stdio.h>#include<string.h>#include<stdlib.h>void CountingSort(int *A,int len,int k){    int *B = new int[len]; //输出数组    memset(B,0,len*sizeof(int));    int *C = new int[k+1]; //临时数组    memset(C,0,(k+1)*sizeof(int));        for(int i=0;i<len;i++)    {        C[A[i]] = C[A[i]]+1; //C[i]为数组A中i值的个数    }    for(int j=1;j<=k;j++)    {        C[j]=C[j]+C[j-1]; //C[i]为数组A中值小于等于i的元素个数    }    for(int t = len-1;t>=0;t--) //倒过来取t以保证stable-sort    {        B[C[A[t]]-1] = A[t];        C[A[t]] = C[A[t]]-1;    }    memcpy(A,B,len*sizeof(int));    delete[] B;    B=NULL;    delete[] C;    C=NULL;}int maxValue(int *A,int len){    if(A == NULL)    {        printf("A is NULL\n");        exit(0);    }    int max = A[0];    for(int i=0;i<len;i++)    {        if(A[i]>max)        {            max = A[i];        }    }    return max;}int main(){    int A[]={3,10,4,24,5,10,3,16};    int len = sizeof(A)/sizeof(int);    int k = maxValue(A,len);    CountingSort(A,len,k);    for(int i=0;i<len;i++)    {        printf("%d ",A[i]);    }    printf("\n");    return 0;}

 

计数排序