第八章線性時間排序之“桶排序BUCKET-SORT”

來源:互聯網
上載者:User

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.