十大排序算法-------【桶排序】详解(Java源码)

桶排序是计数排序的升级版。它利用了函数的映射关系,高效与否的关键就在于这个映射函数的确定。桶排序的工作原理:假设输入数据服从均匀分布,将数据分到有限数量的桶里面,每个桶再分别排序(有可能再次使用到排序排序算法或者是以递归的方式继续使用桶排序进行排序)。

  1. 算法描述
    1. 设置一个定量的数组当作空桶;
    2. 遍历输入数据,并且把数据一个一个放到对应的桶里面去;
    3. 对每个不是空的桶进行排序。
    4. 从不是空的桶里面把排序好的数据进行拼接;
  2. 十大排序算法-------【桶排序】详解(Java源码)_第1张图片
  3. 代码:
private static void tongPaiXu(int[] arrays) {

        int min = arrays[0], max = arrays[0];

        for (int i = 0; i < arrays.length; i++) {

               min = min > arrays[i] ? arrays[i] : min;

               max = max < arrays[i] ? arrays[i] : max;

        }



        int[][] arrayss = new int[max / 10 + 1][];



        for (int i = 0; i < arrays.length; i++) {

               int j = arrays[i] / 10;



               if (arrayss[j] == null) {

                      int[] temp = new int[1];

                      temp[0] = arrays[i];

                      arrayss[j] = temp;

               } else {

                      int length = arrayss[j].length;

                      int[] temp = new int[length + 1];

                      zhuanyiShuZu(arrayss[j], temp);

                      temp[length] = arrays[i];

                      arrayss[j] = temp;

               }

        }



        for (int i = 0, a = 0; i < arrayss.length; i++) {

               if (arrayss[i] != null) {



                      if (arrayss[i].length == 1) {

                             arrays[a++] = arrayss[i][0];

                             System.out.println(arrayss[i][0]);

                      } else if (arrayss[i].length > 1) {



                             for (int j = 0; j < arrayss[i].length; j++) {

                                    int min2 = arrayss[i][j];

                                    for (int j2 = j; j2 < arrayss[i].length; j2++) {

                                           if (min2 < arrayss[i][j2]) {

                                                  int temp = arrayss[i][j2];

                                                  arrayss[i][j2] = arrayss[i][j];

                                                  arrayss[i][j] = temp;

                                           }

                                    }

                             }



                             for (int j = 0; j < arrayss[i].length;) {

                                    System.out.println(arrayss[i][j]);



                                    arrays[a++] = arrayss[i][j++];

                             }



                      }

               }

        }



}



private static void zhuanyiShuZu(int[] arrays1, int[] arrays2) {

        System.out.println(arrays1.length + ", " + arrays2.length);

        for (int i = 0; i < arrays1.length; i++) {

               arrays2[i] = arrays1[i];

        }

}

 

  1. 算法分析:桶排序最好的情况下就是使用线性时间O(n),桶排序的时间复杂度,取决于对各个桶之间数据进行排序的时间复杂度,因为其他部分时间复杂度都为O(n)。很显然,桶划分的越小,各个桶之间的数据越少,排序所用的时间也会越少,但是相应的空间消耗就会增大。

 

你可能感兴趣的:(JavaSE)