1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
| public class BucketSort { public static void main(String[] args) { int[] arr = {1, 2, 6, 9}; bucketSort(arr); }
public static void bucketSort(int[] arr) { // 找出最大值和最小值 int max = 0; int min = 0; for (int i = 0; i < arr.length; i++) { max = Math.max(arr[i], max); min = Math.min(arr[i], min); }
// 创建桶的初始值 int buckedNum = (max - min)/arr.length + 1; ArrayList<ArrayList<Integer>> buckedArr = new ArrayList<>(buckedNum); for (int i = 0; i < buckedNum; i++) { buckedArr.add(new ArrayList<>()); }
// 数组元素放入不同的桶中 for (int i = 0; i < arr.length; i++) { int num = (arr[i] - min) / arr.length; buckedArr.get(num).add(arr[i]); }
// 每个桶内元素自排序后,依次放入到新数组中 int index = 0; int[] sortedArr = new int[arr.length]; for (int i = 0; i < buckedNum; i++) { Collections.sort(buckedArr.get(i));
for (int j = 0; j < buckedArr.get(i).size(); j++) { sortedArr[index++] = buckedArr.get(i).get(j); } }
System.out.println(Arrays.toString(sortedArr)); } }
|