基数排序特点:
1)基数排序的时间是线性的(即 O(n) )。
3)基数排序是稳定的。
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <stdlib.h>
void radixSort(int data[], const int n);
void print(int data[], int n);
/*
* === FUNCTION ======================================================================
* Name: main
* Description:
* =====================================================================================
*/
int main( int argc, char *argv[] )
{
int N, i;
printf ( "How many numbers to test: " );
scanf ( "%d", &N );
int *data = malloc(sizeof(int)*N);
srand((size_t)time(NULL));
for(i=0; i<N; ++i)
{
data[i] = rand()%100;
}
printf ( "Before Sort:\n" );
print(data, N);
radixSort(data, N);
printf ( "\nAfter Sort:\n" );
print(data, N);
free(data);
system("pause");
return EXIT_SUCCESS;
} /* ---------- end of function main ---------- */
void radixSort(int data[], const int n)
{
int temp[n][n+1];// = {{0}}; //temp[n][0]作为存放第n个箱中的元素个数
memset(temp, 0, sizeof(int)*n*(n+1));
int i, j, k, divi=1, reste=1, flag=1;
while( flag )
{
flag = 0;
divi = reste;
reste *= 10;
for(i=0; i<n; ++i)
{ //将数组data[]装进temp箱中
if( (k = (data[i] % reste) / divi) ) //若k不全为0,则还可以装箱
flag = 1;
++temp[k][0];
temp[k][ temp[k][0] ] = data[i];
}
j = 0;
for(i=0; i<n; ++i)
{ //将temp箱中元素放回数组data[]中
if( temp[i][0] )
{ //把第i个箱中的元素放回data[]原数组里面
for(k=1; k<=temp[i][0]; ++k)
data[j++] = temp[i][k];
}
}
for(i=0; i<n; ++i)
{// 把箱中元素个数置1,即清空箱中元素
temp[i][0] = 0;
}
}
}
void print(int data[], int n)
{
int i;
for(i=0; i<n; ++i)
{
printf ( "%d ", data[i] );
}
printf ( "\n" );
}