void count_sort_spec_bit(const int *arr, int bit, int *dest, int first, int last, int scale = 10)// decimal base as default.
{ //this algorithm use both the index and the value of an array to represent data.
int *const bitset = new int[last - first];
std::fill(bitset, bitset + last - first, 0);
for(int i = first; i != last; ++i)
{
int pow10 = 1;
int ite = bit;
for(; ite != 0; --ite, pow10 *= 10)
;
bitset[i] = arr[i] / pow10 % 10;
}
int *host = new int[scale];
std::fill(host, host + scale, 0);
//host[i]: count of values which are equal to i. eg: host[2] == 1,
//means there are two '2'.
for(int i = 0; i < last - first; ++i)
++host[bitset[i]];
//host[i]: count of values which are not greater than i. eg: host[2] = 3,
//means there are 3 numbers less or equal to 2.
for(int i = 1; i < scale; ++i)
host[i] += host[i - 1];
//place the number.
for(int i = last - 1; i >= first; --i)
dest[host[bitset[i]] - 1] = arr[i], --host[bitset[i]];
//clean up.
delete []bitset;
delete []host;
host = NULL;
}
void RadixSort(const int *srcArray, int* destArray, int nCount)
{
ASSERT(nCount > 0);
int *pTemp = new int[nCount];
std::copy(srcArray, srcArray + nCount, pTemp);
for(int nMax = *(std::max_element(pTemp, pTemp + nCount)), i = 0;
nMax != 0; nMax /= 10, ++i)
{
count_sort_spec_bit(pTemp, i, destArray, 0, nCount);
std::copy(destArray, destArray + nCount, pTemp);
}
delete []pTemp;
pTemp = NULL;
}