問題描述:ios
輸入是由一個隨機過程產生的[0, 1)區間上均勻分佈的實數。將區間[0, 1)劃分爲n個大小相等的子區間(桶),每桶大小1/n:[0, 1/n), [1/n, 2/n), [2/n, 3/n),…,[k/n, (k+1)/n ),…將n個輸入元素分配到這些桶中,對桶中元素進行排序,注意,這裏對每一個桶中的元素進行排序其實能夠選擇不少算法,《算法導論》上是用了插入排序。算法
我在不少地方都看到有關這個問題的描述,發現不少人寫的代碼並非《算法導論》上的桶排序,而是基數排序,二者的過程並不同,雖然有部分過程相似。數組
桶排序要求輸入數組中的數據是均勻分佈在 [0, 1)上的,因而我用隨機數產生了一系列[0, 1)之間的數。spa
即便輸入數據不服從均勻分佈,桶排序也仍然能夠在線性時間內完成,只要輸入數據知足下列性質:全部桶的大小的平方和總的元素數呈線性關係,3d
那麼桶排序的時間複雜度就依舊是 Θ(n)。指針
下面的插入排序部分是基於以前插入排序寫的。 code
-------------------------------------------代碼------------------------------------------------ blog
1 // 桶排序.cpp: 定義控制檯應用程序的入口點。 2 // 3 4 #include "stdafx.h" 5 #include <iostream> 6 #include <vector> 7 #include <cstdlib> 8 #include <ctime> 9 10 using namespace std; 11 12 #define N 999 //三位小數。 13 14 int insertion_sort(vector<double> &A)//按升序排列 15 { 16 double key = 0; 17 int j = 0; 18 for (int i = 0; i < A.size(); i++)//依次取出原數組中的數 19 { 20 key = A[i]; 21 j = i - 1; 22 while (j >= 0 && A[j] > key)//若是按降序排列則改爲j >= 0 && a[j] < key 23 { 24 A[j + 1] = A[j]; 25 j--; 26 } 27 A[j + 1] = key; 28 } 29 return 0; 30 } 31 32 int BUCKET_SORT(vector<double> &A)//數組A中的數據均勻地分佈在[0,1)的範圍中,那麼咱們把這個範圍分紅 10 段,對應10個桶 33 { 34 vector<vector<double>> bucket(10);//模擬二維數組,用指針數組也行 35 int temp; 36 for (int i = 0; i < A.size(); i++) 37 { 38 temp = (int)(A[i] * 10); 39 bucket[temp].push_back(A[i]); 40 } 41 42 for (int i = 0; i < 10; i++)//對每一個桶進行插入排序 43 { 44 insertion_sort(bucket[i]); 45 } 46 47 int ptr = 0; 48 for (int i = 0; i < 10; i++) 49 for (int j = 0; j < bucket[i].size(); j++) 50 A[ptr++] = bucket[i][j]; 51 return 0; 52 } 53 54 int main() 55 { 56 vector<double> A; 57 double temp; 58 srand(time(NULL));//設置隨機數種子,使每次獲取的隨機序列不一樣。 59 60 for (int i = 0; i < 10; i++) 61 { 62 temp = rand() % (N + 1) / (float)(N + 1);//生成0-1間的隨機數。 63 A.push_back(temp); 64 } 65 for (auto c : A) 66 cout << c << ends; 67 cout << endl; 68 69 BUCKET_SORT(A); 70 for (auto c : A) 71 cout << c << ends; 72 cout << endl; 73 74 return 0; 75 }
運行結果以下:排序