template<typename T>
void chain<T>::binSort(int range)
{
// 创建并初始化箱子
chainNode<T> **bottom, **top; // 底为首,顶为尾
bottom = new chainNode<T>* [range + 1]; // 指向箱子尾部 chainNode 节点的指针
top = new chainNode<T>* [range + 1]; // 指向箱子首部 chainNode 节点的指针
for (int b = 0; b <= range; b++)
bottom[b] = nullptr;
// 把链表节点分配到箱子
for (; firstNode != nullptr; firstNode = firstNode->next)
{// 把首节点 firstNode 加到箱子中
int theBin = firstNode->element; // 元素类型转换到整型 int
if (bootom[theBin] != nullptr)
bottom[theBin] = top[theBin] = firstNode;
else
{// 箱子不空
top[theBin]->next = firstNode; // 把 firstNode 所指节点添加到顶部
top[theBin] = firstNode; // 并把顶部节点指针 top[theBin] 指向这个新添加的节点
}
}
// 把箱子中的节点收集到有序链表
chainNode<T> *y = nullptr;
for (int theBin = 0; theBin <= range; theBin++)
if (bottmm[theBin] != nullptr)
{// 箱子不空
if (y == nullptr) // 第一个非空箱子在 for 循环中只会遇到一次
firstNode = bottom[theBin];
else // 不是第一个非空箱子
y->next = bottom[theBin];
y = top[theBin]; // 把 y 指向前大链表尾结点,为链接下一个箱子的链做准备
}
if (y != nullptr)
y->next = nullptr;
delete [] bottom;
delete [] top;
}