1. 桶排序将数据区间划分为若干个k个相同大小的子区间,称为桶。将n个数字分别送到各个桶中,如果输入数据是均匀分布在各个桶中,桶排序的时间代价是O(n),所以桶排序的速度很快。在桶排序完成后,只需对每个桶做遍历,即可输出排序的结果。即使输入数据不服从均匀分布,只要所有桶的大小的平方和与总的元素呈线性关系,桶排序也仍然可以在线性时间内完成。
桶排序的伪代码是:
n=A.length
for i=0 to n-1
make B[i] an empty list
for i=1 to n
insert A[i] into list
for i=0 to n-1
sort list B[i] with insertion sort
concatenate the list B[0],B[1],…B[n-1] together in order
2.桶排序的示意图:
3.桶排序的代(数组元素值在0-99之间):
# include <iostream>
using namespace std;
# include <stdlib.h>
struct node
{
int key;
node *next;
};
int main()
{
void fsort(int a[],int n);
int a[10]={23,56,80,46,7,91,94,35,76,37};
int i=0;
fsort(a,10);
for(i=0;i<10;i++)
cout<<a[i]<<endl;
system("pause");
return 0;
}
void fsort(int a[],int n) //桶排序
{
node **b=(node **)malloc(sizeof(node));
int i=0;
int k=0;
for(i=0;i<10;i++) //桶的数量为10
{
b[i]=(node *)malloc(sizeof(node));
b[i]->key=0;
b[i]->next=NULL;
}
int j=0;
for(j=0;j<n;j++)
{
node *t=(node *)malloc(sizeof(node));
t->key=a[j];
t->next=NULL;
int m=a[j]/10; //映射到对应的桶
node *p=b[m];
if(p->key==0)
{
b[m]->next=t;
((*b[m]).key)++;
}
else
{
while(p->next!=NULL&&p->next->key<=t->key)
p=p->next;
t->next=p->next;
p->next=t;
((*b[m]).key)++;
}
}
for(i=0;i<10;i++) //将排好序的数字写回数组
for(node *tmp=b[i]->next;tmp!=NULL;tmp=tmp->next)
a[k++]=tmp->key;
}