要對n個數進行排序,就要準備n個桶。先對n個數歸一化,就是把它們除以一個較大的數,使之分布在【0,1)之間,然後對每個桶中的數插入排序,最後合并n個桶。時間複雜度為O(n)。
#include <string.h>#include <time.h>typedef struct _Node {double value;struct _Node *next;}Node;#define BUFFER_SIZE 10void InsertionSort(Node *a,int len){double b[len];int i=0;int j=0;Node *p=a;//儲存指標 if(a==NULL||a->next==NULL){return;}a=a->next;b[0]=a->value;while(a->next!=NULL){j++;i=j-1;while(i>=0&&b[i]>=a->next->value){b[i+1]=b[i];i--;}b[i+1]=a->next->value;a=a->next;}a=p;i=0;while(a->next!=NULL){a->next->value=b[i++];a=a->next;}}void BucketSort(double *a,int len){int i=0;int j=0;Node b[len];Node *tmp=NULL;Node *p=NULL;int index=0;for(i=0;i<len;i++){b[i].next=NULL;}for(i=0;i<len;i++){tmp=(Node*)malloc(sizeof(Node));tmp->value=a[i];tmp->next=NULL;index=(int)(len*a[i]);tmp->next=b[index].next;b[index].next=tmp;} //對每個桶中的鏈表進行插入排序 for(i=0;i<len;i++){InsertionSort(&b[i],len);}//合并各個桶for(i=0,j=0;i<len;i++){p=b[i].next;while(p!=NULL){a[j++]=p->value;p=p->next;}} //釋放堆記憶體for(i=0;i<len;i++){tmp=b[i].next;while(tmp!=NULL){p=tmp->next;free(tmp);tmp=p; }} }int main(){int i=0;double a[BUFFER_SIZE];printf("待排序數組:\n");srand((unsigned)time(NULL));for(i=0;i<BUFFER_SIZE;i++){a[i]=(rand()%100)*1.0/100;//歸一化 printf("%.2f ",a[i]);}printf("\n");BucketSort(a,BUFFER_SIZE);printf("對數組進行桶排序:\n"); for(i=0;i<BUFFER_SIZE;i++){printf("%.2f ",a[i]);}system("pause");return 0;}