private static void BucketSort(int[] a) {
//n为桶的数量
int n = 4;
//判断桶数是否合法
if (n > a.length || n <= 0) {
throw new RuntimeException("桶的数量不合法:" + n);
}
//声明桶存储
ArrayList<LinkedList<Integer>> s = new ArrayList<>(n);
//初始化ArrayList
for (int i = 0; i < n; i++) {
s.add(new LinkedList<>());
}
//获取数组最大最小值
int min = a[0];
int max = a[0];
for (int i : a) {
min = i > min ? min : i;
max = i > max ? i : max;
}
//根据最大最小值计算桶的宽度
int width = (max - min + 1) / n;
//可以删去
System.out.println("桶间隔=" + width);
//数组元素放入桶中
for (int i : a) {
//获取所在的桶编号
int z = (i - min) / (width);
//最后一个桶需要多装的情况
if (z >= n) {
z = n - 1;
}
s.get(z).add(i);
}
//桶内元素排序
for (int i = 0; i < n; i++) {
Collections.sort(s.get(i));
}
int k = 0;
//把桶内元素填入原数组
for (int i = 0; i < n; i++) {
//可以删除的部分开始-----------
int z = (i + 1) * width;
z = z >= (n * width) ? max : (z - 1);
System.out.println("第" + i + "号桶范围:(" + i * width + "~" + z + ");此桶间距"+(z-(i*width))+";元素有:");
//可以删除的部分完-----------
if (s.get(i) != null) {
for (int j : s.get(i)) {
a[k++] = j;
//可以删除
System.out.print(j + " ");
}
}
//可以删去
System.out.println();
}
}
java桶排序
最新推荐文章于 2021-08-12 19:04:20 发布