简单掌握桶排序算法及C++版的代码实现
桶排序介绍
桶排序(BucketSort)的原理很简单,它是将数组分到有限数量的桶子里。
假设待排序的数组a中共有N个整数,并且已知数组a中数据的范围[0,MAX)。在桶排序时,创建容量为MAX的桶数组r,并将桶数组元素都初始化为0;将容量为MAX的桶数组中的每一个单元都看作一个"桶"。
在排序时,逐个遍历数组a,将数组a的值,作为"桶数组r"的下标。当a中数据被读取时,就将桶的值加1。例如,读取到数组a[3]=5,则将r[5]的值+1。
C++实现算法
假设数据分布在[0,100)之间,每个桶内部用链表表示,在数据入桶的同时插入排序。然后把各个桶中的数据合并。
#include<iterator>
#include<iostream>
#include<vector>
usingnamespacestd;
constintBUCKET_NUM=10;
structListNode{
explicitListNode(inti=0):mData(i),mNext(NULL){}
ListNode*mNext;
intmData;
};
ListNode*insert(ListNode*head,intval){
ListNodedummyNode;
ListNode*newNode=newListNode(val);
ListNode*pre,*curr;
dummyNode.mNext=head;
pre=&dummyNode;
curr=head;
while(NULL!=curr&&curr->mData<=val){
pre=curr;
curr=curr->mNext;
}
newNode->mNext=curr;
pre->mNext=newNode;
returndummyNode.mNext;
}
ListNode*Merge(ListNode*head1,ListNode*head2){
ListNodedummyNode;
ListNode*dummy=&dummyNode;
while(NULL!=head1&&NULL!=head2){
if(head1->mData<=head2->mData){
dummy->mNext=head1;
head1=head1->mNext;
}else{
dummy->mNext=head2;
head2=head2->mNext;
}
dummy=dummy->mNext;
}
if(NULL!=head1)dummy->mNext=head1;
if(NULL!=head2)dummy->mNext=head2;
returndummyNode.mNext;
}
voidBucketSort(intn,intarr[]){
vector<ListNode*>buckets(BUCKET_NUM,(ListNode*)(0));
for(inti=0;i<n;++i){
intindex=arr[i]/BUCKET_NUM;
ListNode*head=buckets.at(index);
buckets.at(index)=insert(head,arr[i]);
}
ListNode*head=buckets.at(0);
for(inti=1;i<BUCKET_NUM;++i){
head=Merge(head,buckets.at(i));
}
for(inti=0;i<n;++i){
arr[i]=head->mData;
head=head->mNext;
}
}