Java算法 -- 桶排序

桶排序(Bucket sort)或所谓的箱排序,是一个排序算法,工作的原理是将数组分到有限数量的桶里。每个桶再个别排序(有可能再使用别的排序算法或是以递归方式继续使用桶排序进行排序)。桶排序是鸽巢排序的一种归纳结果。当要被排序的数组内的数值是均匀分配的时候,桶排序使用线性时间({\displaystyle \Theta (n)}大O符号))。但桶排序并不是比较排序,他不受到{\displaystyle O(n\log n)}下限的影响。

桶排序以下列程序进行:

  1. 设置一个定量的数组当作空桶子。
  2. 寻访序列,并且把项目一个一个放到对应的桶子去。
  3. 对每个不是空的桶子进行排序。
  4. 从不是空的桶子里把项目再放回原来的序列中。
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();//输出打印排序
    }
}

桶排序特点:

  1. 速度快简单
  2. 空间利用率低

桶排序适用场景:

数据范围局限或者有特定要求,范围过大,不推荐适用桶算法。

猜你喜欢

转载自www.cnblogs.com/androidsuperman/p/11016934.html