桶排序(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