桶排序(二)

2014-11-23 22:22:05 · 作者: · 浏览: 1
tSort(a, ilen, 10); // 桶排序
58
59 cout << "after sort:";
60 for (i=0; i
61 cout << a[i] << " ";
62 cout << endl;
63
64 return 0;
65 }
复制代码
桶排序 Java实现
实现代码(BucketSort.java)
复制代码
1 /**
2 * 桶排序:Java
3 *
4 * @author skywang
5 * @date 2014/03/13
6 */
7
8 public class BucketSort {
9
10 /*
11 * 桶排序
12 *
13 * 参数说明:
14 * a -- 待排序数组
15 * max -- 数组a中最大值的范围
16 */
17 public static void bucketSort(int[] a, int max) {
18 int[] buckets;
19
20 if (a==null || max<1)
21 return ;
22
23 // 创建一个容量为max的数组buckets,并且将buckets中的所有数据都初始化为0。
24 buckets = new int[max];
25
26 // 1. 计数
27 for(int i = 0; i < a.length; i++)
28 buckets[a[i]]++;
29
30 // 2. 排序
31 for (int i = 0, j = 0; i < max; i++) {
32 while( (buckets[i]--) >0 ) {
33 a[j++] = i;
34 }
35 }
36
37 buckets = null;
38 }
39
40 public static void main(String[] args) {
41 int i;
42 int a[] = {8,2,3,4,3,6,6,3,9};
43
44 System.out.printf("before sort:");
45 for (i=0; i
46 System.out.printf("%d ", a[i]);
47 System.out.printf("\n");
48
49 bucketSort(a, 10); // 桶排序
50
51 System.out.printf("after sort:");
52 for (i=0; i
53 System.out.printf("%d ", a[i]);
54 System.out.printf("\n");
55 }
56 }
复制代码
上面3种实现的原理和输出结果都是一样的。下面是它们的输出结果:
before sort:8 2 3 4 3 6 6 3 9
after sort:2 3 3 3 4 6 6 8 9