思想:通过对关键字进行“分配”和“收集”,将相同的关键字放入同一个箱子中(分配),即一个箱子中的所有关键字都是相同的,然后再将所有的箱子链接起来(收集)就得到了有序的链表。
一个例子
step a 输入链表
step b 分配
step c 收集
总的来说,该算法的时间复杂度是线性的即O(n)
#include <cstdlib>
#include <iostream>
using namespace std;
typedef struct LinkNode
{
int score;
LinkNode *next;
} LNode, *Node;
void createLinkList(Node h, int n);
void binSort(Node h, int n);
void display(Node h);
int main()
{
int n;
cin >> n;
Node h = new LNode[1];
h->next = nullptr;
createLinkList(h, n);
binSort(h, n);
display(h);
system("pause");
return 0;
}
void createLinkList(Node h, int n)
{ //头插法
while (n)
{
int score;
Node r = new LNode[1];
cin >> score;
r->score = score;
r->next = h->next;
h->next = r;
--n;
}
}
void binSort(Node h, int n)
{
Node bin = new LNode[n];
for (int i = 0; i < n; i++)
bin[i].next = nullptr;
Node p, pr;
p = h->next;
while (p)
{ //分配
pr = p;
p = p->next;
pr->next = bin[pr->score].next;
bin[pr->score].next = pr;
}
h->next = nullptr;
for (int i = n - 1; i >= 0; i--)
{ //收集
while (bin[i].next)
{
Node r = bin[i].next;
bin[i].next = r->next;
r->next = h->next;
h->next = r;
}
}
delete[] bin;
}
void display(Node h)
{
Node p;
p = h;
while (p->next)
{
cout << p->next->score << " ";
p = p->next;
}
cout << endl;
}