Bucket Sort:
Bucket sort assumes that the input is generated by a random process that distributes elements uniformly and independently over the interval [0,1). That is to say, the input number should between 0 and 1. It can use normalization to process the input numbers.
Idea:
Partition 0 to 1 into n part, each part has the same gap(bucket).
Distribution the input num into the bucket.
Then sort each bucket using comparsion algorithms, such as inserting sort.
Realization using Cpp as follow.
#include <iostream>
#include <iomanip>
using namespace std;
float * preProcess(int *A,int p,int q){
int size=q-p+1;
int max=A[p],min=A[p];
for(int i=p+1;i<q;i++){
if(A[i]>max){
max=A[i];
}
if(A[i]<min){
min=A[i];
}
}
int TheGap=max-min;
float *B=new float[size];
for(int i=p;i<q+1;i++){
B[i-p]=(float)(A[i]-min)/TheGap;
}
return B;
}
typedef struct Node{
int val;
Node * next;
}Node,*NodeList;
void BucketSort(float* Arr,int *RealArr,int p,int q){
int size = q-p+1;
NodeList * Table=new NodeList[size+1];
for(int i=0;i<size+1;i++){
Table[i]=NULL;
}
//Insert the number into the bucket
for(int i=0;i<size;i++){
Node * one_node=new Node;
one_node->val=RealArr[p+i];
one_node->next=NULL;
int index=(int)(Arr[p+i]*size);
if(!Table[index]){
Table[index]=one_node;
}else{
Node* pNode=Table[index];
while(pNode->next!=NULL){
pNode=pNode->next;
}
pNode->next=one_node;
}
}
//Sorting in each bucket
for(int i=0;i<size+1;i++){
Node* pFrontNode=Table[i];
Node* pNode;
if(pFrontNode!=NULL)
pNode=pFrontNode->next;
else
pNode=NULL;
while(pFrontNode!=NULL&&pNode!=NULL){
Node* qFrontNode=NULL;
Node* qNode=Table[i];
Node* tmpPNodeNext;
while(qNode!=pNode){
if(qNode->val>pNode->val){
if(qFrontNode!=NULL){
tmpPNodeNext=pNode->next;
pFrontNode->next=pNode->next;
pNode->next=qNode;
qFrontNode->next=pNode;
break;
}else{
tmpPNodeNext=pNode->next;
pFrontNode->next=pNode->next;
pNode->next=qNode;
Table[i]=pNode;
break;
}
}
if(!qFrontNode){
qFrontNode=Table[i];
}else{
qFrontNode=qFrontNode->next;
}
qNode=qNode->next;
}
if(qNode!=pNode){
pNode=tmpPNodeNext;
}
else{
pNode=pNode->next;
pFrontNode=pFrontNode->next;
}
}
}
//OutPut
for(int i=0;i<size+1;i++){
cout<<setw(3)<<i;
Node* pNode=Table[i];
while(pNode!=NULL){
cout<<setw(8)<<setprecision(2)<<pNode->val;
pNode=pNode->next;
}
cout<<endl;
}
}
int main(){
int A[10]={1,5,3,6,2,7,2,4,7,3};
float *B = preProcess(A,0,9);
BucketSort(B,A,0,9);
return 0;
}
While you use the inserting sort, the worst case will be O(n^2). You can substitute with the merge sort or quicket sort to decline the worst case to O(nlgn).
BTW:
From some point, it looks a bit like the hash algorithm which use list to handle the collision.