桶排序

桶排序

概述
  • 桶排序Bucket Sort从1956年就开始被使用,该算法的基本思想是由E. J. Issac R. C. Singleton提出来。
  • 桶排序是一种效率很高的排序算法,它的时间复杂度为O(N+M),(N个元素,范围为0--M),但桶排序有一定的限制,必须为非负整数,而且元素不宜过大
  • 设待排序序列的元素取值范围为0到m,则我们新建一个大小为m+1的临时数组并把初始值都设为0,遍历待排序序列,把待排序序列中元素的值作为临时数组的下标,找出临时数组中对应该下标的元素使之+1;然后遍历临时数组,把临时数组中元素大于0的下标作为值按次序依次填入待排序数组,元素的值作为重复填入该下标的次数,遍历完成则排序结束序列有序。
例子
  • 假设a={8,2,3,4,3,6,6,3,9}, max=10。此时,将数组a的所有数据都放到需要为0-9的桶中。如下图:
  • 桶排序
     public static void bucketSort(int[] a, int max) {
         int[] buckets;
 
         if (a==null || max<1)
             return ;
 
         // 创建一个容量为max的数组buckets,并且将buckets中的所有数据都初始化为0。
         buckets = new int[max];
 
         // 1. 计数
         for(int i = 0; i < a.length; i++) 
             buckets[a[i]]++; 
 
         // 2. 排序
         for (int i = 0, j = 0; i < max; i++) {
             while( (buckets[i]--) >0 ) {
                 a[j++] = i;
             }
         }
 
         buckets = null;
     }
 
     public static void main(String[] args) {
         int i;
         int a[] = {8,2,3,4,3,6,6,3,9};
 
         System.out.printf("before sort:");
         for (i=0; i<a.length; i++)
             System.out.printf("%d ", a[i]);
         System.out.printf("
");
 
         bucketSort(a, 10); // 桶排序
 
         System.out.printf("after  sort:");
         for (i=0; i<a.length; i++)
             System.out.printf("%d ", a[i]);
         System.out.printf("
");
     }
//结果
before sort:8 2 3 4 3 6 6 3 9 
after  sort:2 3 3 3 4 6 6 8 9