算法__桶排序

上一次的計數排序不能對浮點數排序,所以有了桶排序。桶排序: 新建一個集合,每個元素中是一個集合來存儲一個局域的數,然後遍歷這個集合。

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;
    }

 

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