#include <stdio.h>
#include <stdlib.h>
typedef struct elem {
int val;
struct elem *next;
} Elem;
#define BUFSIZE 10
// 100以内
void BucketSort(int *A, int n)
{
Elem **B = (Elem **)malloc(n * sizeof(Elem *));
if (!B) {
printf("B malloc error\n");
return ;
}
for (int i = 0; i < n; i++)
B[i] = NULL;
for (int i = 0; i < n; i++) {
Elem *p = (Elem *)malloc(sizeof(Elem));
if (!p) {
printf("p malloc error\n");
return ;
}
p->val = A[i];
p->next = NULL;
if (B[A[i]/10] == NULL) {
B[A[i]/10] = p;
} else {
Elem *q = B[A[i]/10];
if (p->val < q->val) { // 在头部插入
p->next = B[A[i]/10];
B[A[i]/10] = p; // 这里的B[A[i]/10]千万不能用q,坑
} else {
Elem *prev = q; // 保存前一个节点
while (p->val >= q->val) {
prev = q;
q = q->next;
}
p->next = prev->next;
prev->next = p;
}
}
}
for (int i = 0, j = 0; i < n; i++) {
Elem *pe = B[i];
while (pe) {
Elem *tmp = pe;
A[j++] = pe->val;
pe = pe->next;
free(tmp);
}
}
free(B);
}
int main()
{
int A[BUFSIZE] = {8, 17, 39, 26, 72, 94, 21, 12, 23, 68};
int n = sizeof(A) / sizeof(A[0]);
for (int i = 0; i < n; i++)
printf("%d\t", A[i]);
printf("\n");
BucketSort(A, n);
for (int i = 0; i < n; i++)
printf("%d\t", A[i]);
printf("\n");
system("pause");
return 0;
}