[資料結構]——桶排序

來源:互聯網
上載者:User

一,桶排序

以下代碼轉自:桶排序

#include <iostream>   #include <list>      using namespace std;      struct Node   {       double value;       Node *next;   };   //桶排序主程式   void bucketSort(double* arr, int length)   {       Node key[10];       int number = 0;       Node *p, *q;//插入節點臨時變數       int counter = 0;       for(int i = 0; i < 10; i++)       {           key[i].value = 0;           key[i].next = NULL;       }          for(int i = 0; i < length; i++)       {           Node *insert = new Node();           insert->value = arr[i];           insert->next = NULL;           number = arr[i] * 10;           if(key[number].next == NULL)           {               key[number].next = insert;           }           else           {               p = &key[number];               q = key[number].next;               while((q != NULL) && (q->value <= arr[i]))               {                   q = q->next;                   p = p->next;               }               insert->next = q;               p->next = insert;           }       }       for(int i = 0; i < 10; i++)       {           p = key[i].next;           if(p == NULL)               continue;           while(p != NULL)           {               arr[counter++] = p->value;               p = p->next;           }       }   }      int main()   {       double a[] = {0.78, 0.17, 0.39, 0.26, 0.72, 0.94, 0.21, 0.12, 0.23, 0.68};       bucketSort(a, 10);       for(int i = 0; i < 10; i++)       {           cout << a[i] << " ";       }       cout << endl;       return 0;   }  
【例】要將一副混洗的52張撲克牌按點數A<2<…<J<Q<K排序,需設定13個"箱子",排序時依次將每張牌按點數放入相應的箱子裡,然後依次將這些箱子首尾相接,就得到了按點數遞增序排列的一副
一般情況下每個箱子中存放多少個關鍵字相同的記錄是無法預料的,故箱子的類型應設計成鏈表為宜。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.