基本思想
首先桶排序假设输入数据服从均匀分布,输入是由一个随机过程产生,该过程将元素均匀,独立地分布在[0,1)区间上.然后桶排序将[0,1)区间划分成n个相同大小的区间,或称为桶.然后,将n个输入数分别放到各个桶中.因为输入数据是均匀独立地分布在[0,1)上的,所以不会有很多数落在一个桶中.最后为了得到结果,先对每个桶中的数进行排序,然后遍历所有桶,按次序把每个桶中的元素拿出来.
图解

代码
伪代码

C代码
#include <stdio.h>
#include <stdlib.h>
#define N 20
struct node {
float key;
struct node * next;
};
void Bucket_sort(float * a, int len)//桶排序
{
int i;
struct node ** b = (struct node **)malloc(sizeof(struct node *) * len);
//桶初始化
for(i = 0; i < len; i++)
{
b[i] = (struct node *)malloc(sizeof(struct node));
b[i]->key = -999;
b[i]->next = NULL;
}
//插入数据并排序
for(i = 0; i < len; i++)
{
struct node * p = (struct node *)malloc(sizeof(struct node));
p->key = a[i];
p->next = NULL;
int index = a[i]/10;
struct node * t = b[index];
//插入排序
while((t->next!=NULL)&&(t->next->key <= p->key))
t = t->next;
p->next = t->next;
t->next = p;
}
int j = 0;
for(i = 0; i < len; i++)//从b中导出数据
{
struct node * temp = b[i]->next;
while(temp != NULL)
{
a[j++] = temp->key;
temp = temp->next;
}
}
}
void Show(float * a, int len)
{
int i = 0;
for(i = 0; i < len; i++)
printf("%f ", a[i]);
printf("\n");
}
int main()
{
float a[] = {0.78, 0.17, 0.39, 0.26, 0.72, 0.94, 0.21, 0.12, 0.23, 0.68};
int len = sizeof(a) / sizeof(float);
Show(a,len);
Bucket_sort(a,len);
Show(a,len);
return 0;
}
时间复杂度
时间复杂度为O(n),前提条件是输入数据服从均匀分布,或所有桶的大小的平方和与总的元素数呈线性关系,桶排序也可在线性时间内完成.