import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
class My {
public void bucketSort(double[] arr) {
int n = arr.length;
double max = arr[0];
double min = arr[0];
for (double a : arr) {
if (max < a) {
max = a;
}
if (min > a) {
min = a;
}
}
//这里会涉及Double与double类型的自动装箱与拆箱
List<List<Double>> buckets = new ArrayList<>();//buckets是个装桶的桶
for (int i = 0; i < n; i++) {
buckets.add(new ArrayList<>());//共设置n个桶
}
for (double a : arr) {
//max - min + 1 这里的+1是使总区间稍微大一点,方便处理边界,如果是数据是int类型,可以选择+n
double section = (max - min + 1) / n; //划分每个桶的区间范围大小,区间左闭右开
int index = (int) ((a - min) / section); //得出元素a所属的桶号
buckets.get(index).add(a);
}
int i = 0;//把各个桶中的元素排好序,并全部塞回arr数组
for (List<Double> bucket : buckets) {
Collections.sort(bucket);
for (Double a : bucket) {
arr[i] = a;
i++;
}
}
}
public static void main(String[] args) {
double[] arr = {5.1, 4.3, 6.5, 23.8, 2.4, 6.8, 16.1, 33.5, 36.2, 41.4};
My my = new My();
my.bucketSort(arr);
System.out.println(Arrays.toString(arr));
}
}