算法__桶排序

上一次的计数排序不能对浮点数排序,所以有了桶排序。桶排序: 新建一个集合,每个元素中是一个集合来存储一个局域的数,然后遍历这个集合。

2.5

1.3

3.6 0.3 5.5

桶的数量:可以是数的个数。桶的区域 = (最大数 -  最小数)/  (桶的个数  -  1)  =  (5.5 - 0.3)/  4  =  1.3 

如图所示,最后一个只存最大的数。然后,遍历数组,存入到每个范围的桶中。最后,对每个桶排序,将每个桶的数字输出。

代码如下:

    //桶排序
    private double[] bucketSort(double arry[]) {
        double max = arry[0], min = arry[0];
        int size = arry.length;
        for (int i = 0; i < size; i++) {
            if (max < arry[i])
                max = arry[i];
            if (min > arry[i])
                min = arry[i];
        }
        //初始化桶排序集合
        double number = max - min;
        List<LinkedList<Double>> bucketList = new ArrayList<LinkedList<Double>>();
        //放进桶中
        for (int i = 0; i < size; i++) {
            bucketList.add(new LinkedList<Double>());
        }

        for (int i = 0; i < size; i++) {
            int numbers = (int) ((arry[i] - min) * (size - 1) / number);
            bucketList.get(numbers).add(arry[i]);
        }

        for (int i = 0; i < bucketList.size(); i++) {
            Collections.sort(bucketList.get(i));
        }

        int location = 0;
        double[] sortArray = new double[size];
        for (int i = 0; i < bucketList.size(); i++) {
            for (Double doubles : bucketList.get(i)) {
                sortArray[location] = doubles;
                location++;
            }
        }

        System.out.print(Arrays.toString(sortArray));
        return sortArray;
    }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章