桶排序(Bucket sort)或所谓的箱排序,是一个排序算法,工做的原理是将数组分到有限数量的桶里。每一个桶再个别排序(有可能再使用别的排序算法或是以递归方式继续使用桶排序进行排序)。桶排序是鸽巢排序的一种概括结果。当要被排序的数组内的数值是均匀分配的时候,桶排序使用线性时间((大O符号))。但桶排序并非比较排序,他不受到
下限的影响。java
桶排序如下列程序进行:算法
public class BucketSort { private int[] buckets; private int[] array; public BucketSort(int range, int[] array) { this.buckets = new int[range]; this.array = array; } /*排序*/ public void sort() { if (array != null && array.length > 1) { for (int i = 0, arrayLength = array.length; i < arrayLength; i++) { int i1 = array[i]; buckets[i1]++; } } } /*排序输出*/ public void sortOut() { //倒序输出数据 // for (int i=buckets.length-1; i>=0; i--){ // for(int j=0;j<buckets[i];j++){ // System.out.print(i+"\t"); // } // } for (int i = 0; i <= buckets.length - 1; i++) { for (int j = 0; j < buckets[i]; j++) { System.out.print(i + "\t"); } } } public static void main(String[] args) { testBucketsSort(); } private static void testBucketsSort() { int[] array = {5, 7, 17, 3, 5, 22, 4, 15, 8, 6, 4, 1, 2}; BucketSort bs = new BucketSort(23, array); bs.sort(); bs.sortOut();//输出打印排序 } }
桶排序特色:数组
桶排序适用场景:this
数据范围局限或者有特定要求,范围过大,不推荐适用桶算法。code