1. 分析
/*10.基数排序(RadixSort)
1. 分桶: 按照个位分桶
2. 把数据装入对应桶中;(尾添加)
3. 把数据倒回原数组
4. 再按照 十位分桶,重复2-3
5. 再按照 百位分桶,从复2-3
6. 直到最高位。
例子:
原数组:23,653,121,53,110,15,482,663,35,336,57,30,61
1. 按个位
桶: 0,1,2,3,4,5,6
桶0:110,30
桶1:121,61
桶2:482
桶3:23,653,53,663
桶4:
桶5:15,35
桶6:336
放回:110,30,121,61,482,23,653,53,663,15,35,336
2. 按照十位(实际7个桶,在此为便于理解)
桶0:
桶1:110,15
桶2:121,23
桶3:30,35,336
桶4:
桶5:653,53
桶6:61,663
桶7:
桶8:482
放回:110,15,121,23,30,35,336,653,53,61,663,482
3. 按照百位
桶0:15,23,30,35,53,61
桶1:110,121
桶2:
桶3:336
桶4:482
桶5:
桶6:653,663
放回:15,23,30,35,53,61,110,121,3336,482,653,663(有序)
实现方法:循环
*/
2. 源码
typedef struct radix
{
int nValue;
struct radix* pNext;
}Radix;
void LSD(int arr[], int nLength, Radix** pRadix, int nBit)
{
int nBase = 1;
int i;
int nIndex;
int nTemp;
Radix* pTemp = NULL;
Radix* pNode = NULL;
while(nBit)
{
nBase *= 10;
nBit--;
}
for (i = 0; i < nLength; i++)
{
nIndex = arr[i] / nBase % 10;
pNode = (Radix*)malloc(sizeof(Radix));
pNode->nValue = arr[i];
pNode->pNext = NULL;
pTemp = pRadix[nIndex];
if (pTemp == NULL)
{
pRadix[nIndex] = pNode;
}
else
{
while (pTemp->pNext)
pTemp = pTemp->pNext;
pTemp->pNext = pNode;
}
}
for (nTemp = 0, i = 0; i < 10; i++)
{
pTemp = pRadix[i];
while (pTemp)
{
arr[nTemp] = pTemp->nValue;
nTemp++;
pNode = pTemp;
pTemp = pTemp->pNext;
free(pNode);
pNode = NULL;
}
}
memset(pRadix, 0, sizeof(Radix*)* 10);
}
void RadixSort(int arr[], int nLength)
{
if(arr == NULL || nLength<=0)
{
printf("RadixSort :invalid input!\n");
return ;
}
int Max = arr[0];
int nCount = 0;
int nTemp;
for(nTemp=0;nTemp<nLength; nTemp++)
{
if(Max < arr[nTemp])
Max = arr[nTemp];
}
nTemp = Max;
while(nTemp)
{
nTemp /= 10;
nCount++;
}
Radix* * pRadix = (Radix**)malloc( sizeof(Radix*) *10);
memset(pRadix, 0, sizeof(Radix*) *10);
for(nTemp=0; nTemp < nCount;nTemp++)
{
LSD(arr, nLength, pRadix, nTemp);
}
free(pRadix);
pRadix = NULL;
return;
}
void Print(char* pStr, int arr[], int nLength)
{
printf("%s : ", pStr);
for(int i=0;i<nLength;i++)
{
printf("%d ",arr[i]);
}
printf("\n");
}
int main()
{
int arr[] = {4,5,52,8,4423,43,126,45,187,615,33,18,27,457};
int nLength = sizeof(arr)/sizeof(arr[0]);
RadixSort(arr,nLength);
Print("RadixSort", arr, nLength);
}