The basic idea of the cardinal sort is to sort each digit of the number, sort the digits first, and then 10 bits, hundred .... In order to sort each one, a stable sorting algorithm is required, such as the sort of counts discussed previously. Take a three-bit integer as an example, the process is this:
The algorithm can also achieve linear complexity. Here is the code. (Well, I know it's very well written.) )
#include <stdio.h> #define NUM 10//array elements void Counting_sort (int a[],int b[],int c[],int atemp[]); int main () {int i;i NT J;int a[10] = {326,54,512,13,9,71,92,61,53,19}; Input Arrayint atemp[10];int b[10]; Output Arrayint c[10]; Temp all element is not biger than 10//digit sort for (i = 0;i < num;i++) Atemp[i] = A[i]% 10;counting_sort (atemp,b,c,a); for (i = 0;i < num;i++) A[i] = b[i];//10-bit sort for (i = 0;i < num;i++) Atemp[i] = A[i]/ten 10;counting_sort (Atemp,b,c, a); for (i = 0;i < num;i++) A[i] = b[i];//hundred sort for (i = 0;i < num;i++) Atemp[i] = A[i]/10;counting_sort (ATEMP,B, C,a); for (i = 0;i < num;i++) printf ("%d", B[i]);p rintf ("\ n");} Counting sorting algorithm, A is the array to be sorted (one number, to be separated from atemp), B is a sorted array, C is an intermediate array, Atemp is the original array (including three digits) void counting_sort (int a[],int b[],int C[],int Atemp[]) {int i,j;for (i = 0;i < num;i++) C[i] = 0;for (j = 0;j < num;j++) C[a[j]] + = 1;for (i = 1;i < num;i++) C[i] = C[i] + c[i-1];for (j = 9;j >= 0;j--) {B[c[a[j]]-1] = Atemp[j];c[a[j]]-= 1;}}
Base Sorting and C language implementation