桶排序

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;
}


 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值