#include <assert.h>
#include <stdlib.h>
template <typename T>
size_t FindDepth(T iData[], size_t iBegin, size_t iEnd)
{
size_t iMaxDepth = 0;
size_t iCurDepth = 0;
char cData[15] = "";
while (iBegin <= iEnd)
{
iCurDepth = sprintf_s(cData, sizeof(cData), "%d", iData[iBegin]);
iMaxDepth = iMaxDepth>=iCurDepth ? iMaxDepth:iCurDepth;
iBegin++;
}
return iMaxDepth;
}
//compute d^n
static size_t mPow(size_t d, size_t n)
{
assert(d || n);
if (!n)
return 1;
while (--n)
d *= d;
return d;
}
template <typename T>
void RadixSort(T iData[], size_t iBegin, size_t iEnd)
{
T (*piRadix)[10] = new T[iEnd-iBegin+1][10];
size_t iBoxDepth[10];
size_t iDepth = FindDepth(iData, iBegin, iEnd);
for (size_t i = 0; i < iDepth; i++)//扫描数据位数层
{
//桶深度清零
for (size_t k = 0; k < 10; k++)
iBoxDepth[k] = 0;
//分配入桶
for (size_t j = iBegin; j <= iEnd; j++)//扫描数据个数
{
size_t iCurNum = (iData[j]%mPow(10,i+1))/(mPow(10,i));//取当前数据当前位值
piRadix[iBoxDepth[iCurNum]][iCurNum] = iData[j];//将当前值堆入桶中
iBoxDepth[iCurNum]++;
}
//重新排序
size_t r = 0;//已重新排列数据个数
for (size_t s = 0; s < 10; s++)//每一个桶顺序取
{
for (size_t t = 0; t < iBoxDepth[s]; t++)//桶尝试
{
iData[r] = piRadix[t][s];//从桶中取数据
r++;
}
}
}
if (!piRadix)
delete []piRadix;
return;
}
排序算法--基数排序(箱排序的改进)
最新推荐文章于 2024-04-03 20:43:58 发布