//基数排序
template<typename T>
void chain<T>::radixSort(int r,int d) //r为基数,d为按基数分解的个数
{
int m,theBin;
for (int i = 1; i <= d; ++i) //总共排序d次
{
//创建并初始化箱子,箱子的大小就是就是基数r的大小
chainNode<T>**bottom, **top;
bottom = new chainNode<T>*[r];//链表节点构成的数组,不同的数组段的尾节点
top = new chainNode<T>*[r];
for (int b = 0; b < r; ++b)
top[b] = NULL;
//将链表在的节点分配到箱子
for (; firstNode != NULL; firstNode = firstNode->next)//分配完之后链表也就变成了空表
{
m = pow(r, i);
theBin = firstNode->element%m / pow(r, i - 1);
if (top[theBin] == NULL)
top[theBin] = bottom[theBin] = firstNode;
else {
bottom[theBin]->next = firstNode;
bottom[theBin] = firstNode;
}
}
//把箱子中的节点收集到有序链表
chainNode<T>*y = NULL; //负责连接各段链表
for(int theBin=0;theBin<r;++theBin)
if (top[theBin] != NULL)
{
if (y == NULL)
firstNode = top[theBin]; //将第一个非空箱子放入链表
else
y->next = top[theBin]; //后续箱子接着放入
y = bottom[theBin];
}
if (y != NULL)
y->next = NULL; //将表的末尾下一节点置空
delete [] bottom;
delete [] top;
}
}
单链表中基于箱子的基数排序
最新推荐文章于 2021-07-30 09:23:45 发布