1. 分析
/*9.桶排序(BucketSort)
1. 分桶: 按照最高位分桶,最高位相同按照次高位分桶
2. 把数据装入对应桶中;(头添加)
3. 桶内数据排序
4. 把数据倒回原数组
例子:
原数组:123,653,121,453,110,145,487,663,235,336,571
桶: 1, 2,3,4,5,6
桶1:145 110 121 123
桶2:235
桶3:336
桶4:487 453
桶5:571
桶6:663 653
实现方法:循环
*/
2. 源码
typedef struct bucket
{
int nValue ;
struct bucket* pNext;
}Bucket;
void GetMaxMinDropNumber(int arr[] ,int nLength, int* pMax, int* pMin, int* pBase, int* pDropNumber)
{
int i ;
int Max = arr[0];
int Min = arr[0];
int nDrop = 0;
int nBase = 1;
int nMaxIndex = 0;
int nMinIndex = 0;
int nTemp = arr[0];
for(i =0; i< nLength; i++)
{
if( Min > arr[i])
Min = arr[i];
if(Max < arr[i])
Max = arr[i];
}
while(nTemp)
{
nTemp = nTemp/10;
nBase *=10;
}
while(1)
{
nBase /=10;
nMaxIndex = Max/nBase%10;
nMinIndex = Min/nBase%10;
if(nMaxIndex == nMinIndex)
{
nDrop = nMaxIndex*nBase;
Max = Max - nDrop;
Min = Min - nDrop;
}
else
{
break;
}
}
*pMax = nMaxIndex;
*pMin = nMinIndex;
*pDropNumber = nDrop;
*pBase = nBase;
return ;
}
void BucketInnerSort(Bucket* pHead)
{
Bucket* pMark = pHead;
Bucket* pTemp = NULL;
int nTemp;
Bucket* pLastUpdatePos;
while(pMark)
{
pTemp = pHead;
pLastUpdatePos = pHead;
while(pTemp->pNext)
{
if(pTemp->nValue < pTemp->pNext->nValue)
{
nTemp = pTemp->pNext->nValue;
pTemp->pNext->nValue = pTemp->nValue;
pTemp->nValue = nTemp;
pLastUpdatePos = pTemp->pNext;
}
pTemp = pTemp->pNext;
}
if(pLastUpdatePos == pHead)
break;
pMark = pMark->pNext;
}
return ;
}
void BucketSort(int *arr, int nLength)
{
if(arr == NULL ||nLength<=0)
{
printf("CountSort :invalid input! \n");
return ;
}
int i;
int nIndex = 0;
int nMaxIndex;
int nMinIndex;
int nBase;
int nDropNumber = 0;
Bucket* pTemp = NULL;
Bucket* pDel = NULL;
int nTemp;
GetMaxMinDropNumber(arr, nLength, &nMaxIndex, &nMinIndex,&nBase, &nDropNumber);
Bucket* * pBucket = (Bucket**)malloc( sizeof(Bucket*) * (nMaxIndex - nMinIndex + 1) );
memset(pBucket, 0, sizeof(Bucket*) * (nMaxIndex - nMinIndex+1) );
for (i = 0; i < nLength; i++)
{
nIndex = (arr[i] - nDropNumber)/nBase%10;
pTemp = (Bucket*)malloc( sizeof(Bucket));
pTemp->nValue = arr[i];
pTemp->pNext = pBucket[nIndex];
pBucket[nIndex] = pTemp;
}
for (i = 0; i < nMaxIndex - nMinIndex + 1; i++)
{
BucketInnerSort(pBucket[i]);
}
for (nTemp = 0,i=0; nTemp < nMaxIndex - nMinIndex + 1; nTemp++)
{
pTemp = pBucket[nTemp];
while(pTemp)
{
arr[i] = pTemp->nValue;
pDel = pTemp;
pTemp = pTemp->pNext;
i++;
free(pDel);
pDel = NULL;
}
}
free(pBucket);
pBucket = NULL;
}
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 arr2[] = {4001,4562,4532,4218,4723,4443,4812,4445,4387,4065,4933,4118,4127};
BucketSort(arr2,sizeof(arr2)/sizeof(arr2[0]));
Print("Bucket :", arr2, nLength);
return 0;
}