桶式排序是對一個有n個整型元素的數組a[n],其中對任意i,0 <= a[i] <= m的特殊排序算法。
可以對 n==m, n != m分別處理。寫代碼時需要注意的的是a[i]是訪問第i-1個元素,而非第i個。
1
/**//************************************************************************************/
2
/**//* Bucket_Sort.h 桶式排序算法 */
3
/**//* 問題:對一個有n個整型元素a[0],a[1],…,a[n-1]的數組排序,其中0 <= a[i] <= m,任意i */
4
/**//* 程序:運行時間為O(m+n),輔助空間為O(m) */
5
/**//* 當 n=m 時特殊處理,運行時間為O(N), 輔助空間為O(1) */
6
/**//************************************************************************************/
7
8
#include <vector>
9
10
/**//*m != n */
11
void Bucket_Sort_m(int *a, int n, int m)
12

{
13
std::vector<int> temp(m,0);
14
int i;
15
for(i = 0; i != n; ++i) //遍歷a[]
16
++temp[a[i]-1]; //如果有對應于下標的值,標記為1,否則為0
17
18
i = 0;
19
for(int j = 1; j <= m; ++j) //遍歷temp向量
20
if(temp[j-1]) a[i++] = j;
21
22
temp.clear();
23
}
24
25
/**//* m == n */
26
/**//* 最后的結果是a[i-1] = i */
27
void Bucket_Sort(int *a,int n)
28

{
29
for(int i = 1; i <= n; ++i)
30
{
31
while(a[i-1] != i)
32
{
33
int temp = a[a[i-1]-1];
34
a[a[i-1]-1] = a[i-1];
35
a[i-1] = temp;
36
}
37
/**//* 偽代碼:如果假設可以通過a[i]訪問數組的第i個元素,而不是第i-1個 */
38
/**//*while(a[i] != i)
39
{
40
int temp = a[a[i]];
41
a[a[i]] = a[i];
42
a[i] = temp;
43
}
44
*/
45
}
46
}