/*************************************** * ************ Array: * array that to be sorted. * nlength: * length of array * NK: * maximum number that may appear (nk = 9 for a 10-digit number ). **************************************** * **********/void countingsort (INT array [], size_t nlength, int NK) {If (null = array | 0 = nlength | 0 = NK) return; int * COUNT = new int [NK + 1]; memset (count, 0, sizeof (INT) * (NK + 1); int * arrayresult = new int [nlength]; memset (arrayresult, 0, sizeof (INT) * nlength); // count first. Count [idx] is the number of elements whose value is equal to idx. For (INT idx = 0; idx <nlength; idx ++) count [array [idx] ++; // accumulate again. Count [idx] is the number of elements less than or equal to idx for (INT idx = 1; idx <NK + 1; idx ++) Count [idx] = count [idx] + Count [idx-1]; // round-robin From the back to the front (ensuring stable sorting ), sort array [idx] into all the numbers smaller than or equal to array [idx] (count [array [idx] in total) the back of for (INT idx = nLength-1; idx> = 0; idx --) {arrayresult [count [array [idx]-1] = array [idx]; count [array [idx] --;} memcpy (array, arrayresult, sizeof (INT) * nlength); Delete [] count; Delete [] arrayresult ;}